简体   繁体   English

在Java中将时间戳字符串转换为long

[英]Convert timestamp string to long in java

I have to fetch time stamp from DB and retrieve only time and compare two time. 我必须从DB中获取时间戳并仅检索时间并比较两次。

//below are the string values //下面是字符串值

 String st1 = "2015-07-24T09:39:14.000Z";      
 String st2 = "2015-07-24T09:45:44.000Z";

//retrieving only time 09:39:14 //只检索时间09:39:14

 String s = st1.substring(st1.indexOf("T") + 1, st1.indexOf(".0"));

//string to Long. //字符串为Long。

 Long time = Long.parseLong(s);

 Long tim1=Long.valueOf(s).longValue();

Error: 错误:

java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)

Try this way, Example code: 试试这种方式, 示例代码:

java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf("2015-07-24T09:45:44.000Z");
long tsTime2 = ts2.getTime();

The simplest solution would be to use Java 8's Date/Time API 最简单的解决方案是使用Java 8的Date / Time API

LocalDateTime from = LocalDateTime.parse("2015-07-24T09:39:14.000Z", DateTimeFormatter.ISO_DATE_TIME);
LocalDateTime to = LocalDateTime.parse("2015-07-24T09:45:44.000Z", DateTimeFormatter.ISO_DATE_TIME);
System.out.println(from + " - " + to);

LocalTime fromTime = from.toLocalTime();
LocalTime toTime = to.toLocalTime();

System.out.println(fromTime + " - " + toTime);

System.out.println(fromTime + " before " + toTime + " = " + fromTime.isBefore(toTime));
System.out.println(fromTime + " after " + toTime + " = " + fromTime.isAfter(toTime));
System.out.println(fromTime + " equals " + toTime + " = " + fromTime.equals(toTime));
System.out.println(fromTime + " compareTo " + toTime + " = " + fromTime.compareTo(toTime));

Which outputs 哪个输出

2015-07-24T09:39:14 - 2015-07-24T09:45:44
09:39:14 - 09:45:44
09:39:14 before 09:45:44 = true
09:39:14 after 09:45:44 = false
09:39:14 equals 09:45:44 = false
09:39:14 compareTo 09:45:44 = -1

If you're not using Java 8, then use Joda-Time which works in similar way 如果你没有使用Java 8,那么使用Joda-Time ,它以类似的方式工作

Joda-Time example... Joda-Time示例......

import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;
import org.joda.time.format.ISODateTimeFormat;

public class JodaTimeTest {

    public static void main(String[] args) {
        LocalDateTime from = LocalDateTime.parse("2015-07-24T09:39:14.000Z", ISODateTimeFormat.dateTime());
        LocalDateTime to = LocalDateTime.parse("2015-07-24T09:45:44.000Z", ISODateTimeFormat.dateTime());

        LocalTime fromTime = from.toLocalTime();
        LocalTime toTime = to.toLocalTime();

        System.out.println(fromTime + " - " + toTime);

        System.out.println(fromTime + " before " + toTime + " = " + fromTime.isBefore(toTime));
        System.out.println(fromTime + " after " + toTime + " = " + fromTime.isAfter(toTime));
        System.out.println(fromTime + " equals " + toTime + " = " + fromTime.equals(toTime));
        System.out.println(fromTime + " compareTo " + toTime + " = " + fromTime.compareTo(toTime));
    }

}

Which outputs 哪个输出

09:39:14.000 - 09:45:44.000
09:39:14.000 before 09:45:44.000 = true
09:39:14.000 after 09:45:44.000 = false
09:39:14.000 equals 09:45:44.000 = false
09:39:14.000 compareTo 09:45:44.000 = -1

Another option is by using SimpleDateFormat (May not be the best compare to JODA Time) 另一个选择是使用SimpleDateFormat(可能不是最佳比较JODA时间)

public static void main(String[] args) throws ParseException {
        String st1 = "2015-07-24T09:39:14.000Z";
        String st2 = "2015-07-24T09:45:44.000Z";

        String time1 = st1.substring(st1.indexOf("T") + 1, st1.indexOf(".0"));
        String time2 = st2.substring(st2.indexOf("T") + 1, st2.indexOf(".0"));

        Date dateTime1 = new java.text.SimpleDateFormat("HH:mm").parse(time1);
        Date dateTime2 = new java.text.SimpleDateFormat("HH:mm").parse(time2);

        System.out.println(dateTime1.after(dateTime2));

    }

tl;dr TL;博士

myResultSet.getObject(                         // Use JDBC 4.2 or later to get *java.time* objects rather than mere strings.
    … ,                                        // Specify the column in database of type `TIMESTAMP WITH TIME ZONE`.
    Instant.class                              // Extract from database as a `Instant` object in UTC, via JDBC.
)
.atZone( ZoneId.of( "Africa/Tunis" ) )         // Adjust into a time zone other than UTC. Returns a `ZonedDateTime` object.
.toLocalDate()                                 // Extract the date-only value, without time-of-day and without time zone. Returns a `LocalDate` object.
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) )   // Determine the first moment of the day (not always 00:00). Returns a `ZonedDateTime` object.

And… 和…

Duration.between( zdtStartOfDay , zdt )        // Represent the span of time between the first moment of the day and the target moment. Each argument is a `ZonedDateTime` object here.
    .toMillis()                                // Get entire span as a count of milliseconds. Returns a `long` primitive.
  • No need for strings. 不需要字符串。
  • No need for java.sql.Timestamp . 不需要java.sql.Timestamp

java.time java.time

The modern approach uses the java.time classes that supplant the troublesome old legacy classes such as java.sql.Timestamp & Date & Calendar . 现代方法使用java.time类来取代麻烦的旧遗留类,例如java.sql.TimestampDateCalendar

The Answer by MadProgrammer is headed in the right direction by using java.time but uses the wrong class: LocalDateTime class purposely lacks any concept of time zone or offset-from-UTC but our input string does. 通过MadProgrammer答案是在正确的方向上采用java.time为首,但使用了错误的类: LocalDateTime类特意没有时区的任何概念或偏移从-UTC,但我们的输入字符串一样。 The Z on the end of the input String is short for Zulu and means UTC. 输入字符串末尾的ZZulu缩写,表示UTC。 Throwing away valuable information (zone/offset info) is not a good practice. 扔掉有价值的信息(区域/偏移信息)不是一个好习惯。

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction). Instant类表示UTC时间轴上的一个时刻,分辨率为纳秒 (最多九(9)位小数)。

Instant instant = Instant.parse( "2015-07-24T09:39:14.000Z" ) ;

Smart objects, not dumb strings 智能对象,而不是哑弦

I have to fetch time stamp from DB and retrieve only time and compare two time. 我必须从DB中获取时间戳并仅检索时间并比较两次。

below are the string values 下面是字符串值

Use appropriate objects to exchange data with your database, not mere strings. 使用适当的对象与数据库交换数据,而不仅仅是字符串。

As of JDBC 4.2, you can directly exchange java.time objects via getObject & setObject . 从JDBC 4.2开始,您可以通过getObjectsetObject直接交换java.time对象。

Instant instant = myResultSet( … , Instant.class ) ;

You just fetched a date-time directly from a database column of type similar to the SQL-standard TIMESTAMP WITH TIME ZONE . 您只是直接从类似于SQL标准TIMESTAMP WITH TIME ZONE的类型的数据库列中获取日期时间。

For sending data to the database, use a PreparedStatement with placeholders. 要将数据发送到数据库,请使用带有占位符的PreparedStatement

myPreparedStatement.setObject( … , instant ) ;

The Instant object retrieved via JDBC from the database is in UTC, by definition. 根据定义,通过JDBC从数据库检索的Instant对象是UTC。 To get the time-of-day, you must specify the wall-clock time of the region expected by the user (the time zone). 要获取时间,您必须指定用户期望的区域的挂钟时间(时区)。

Specify a proper time zone name in the format of continent/region , such as America/Montreal , Africa/Casablanca , or Pacific/Auckland . continent/region的格式指定适当的时区名称 ,例如America/MontrealAfrica/CasablancaPacific/Auckland Never use the 3-4 letter pseudo-zones such as EST or IST as they are not true time zones, not standardized, and not even unique(!). 切勿使用3-4个字母伪区域,如ESTIST因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;

Apply that time zone to get a ZonedDateTime object. 应用该时区以获取ZonedDateTime对象。 The Instant and the ZonedDateTime represent the same moment , the same point on the timeline. InstantZonedDateTime代表同一时刻 ,即时间轴上的相同点。 This is a crucial concept to understand. 这是一个需要理解的关键概念。 Two friends talking on the phone, one in Québec Canada and one in Paris France will each look up to a clock on the wall simultaneously at the same moment yet see a different time in use by the people of their particular region. 两个朋友在电话上聊天,一个在加拿大魁北克,一个在法国巴黎,每个人同时在墙上同时看到一个钟,但看到他们特定地区的人们使用不同的时间。

ZoneDateTime zdt = instant.atZone( z ) ;

If you care only about the time-of-day, extract a LocalTime object. 如果您只关心时间,请提取LocalTime对象。

LocalTime lt = zdt.toLocalTime(); 

Generate a String in standard ISO 8601 format. 生成标准ISO 8601格式的String

String output = lt.toString();

Generate a string in localized format. 以本地化格式生成字符串。

DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ;
String output = lt.format( f ) ;

But you seem to want a count of something since the start of the day – your Question is not clear. 但是你似乎想要从一天开始就计算一些东西 - 你的问题不明确。 Perhaps you want a count of whole seconds, or milliseconds, or I don't know what. 也许你想要一整秒或几毫秒的计数,或者我不知道是什么。

We must get the start of the day in the desired/expected time zone. 我们必须在期望/预期的时区内开始新的一天。 Do not assume the day starts at the time 00:00:00. 不要假设当天00:00:00开始。 Because of anomalies such as Daylight Saving Time (DST), the day may start at another time such as 01:00:00. 由于夏令时(DST)等异常,该日可能会在另一个时间开始,例如01:00:00。 Let java.time determine the start of the day. 让java.time确定一天的开始。

ZonedDateTime zdtStartOfDay = zdt.toLocalDate().atStartOfDay( z ) ;

Calculate the elapsed span of time as a Duration . 将经过的时间跨度计算为Duration

Duration d = Duration.between( zdtStartOfDay , zdt ) ;

Extract the entire span as a number of whole seconds. 将整个范围提取为整数秒。

long secondsSinceStartOfDay = d.toSeconds() ;

Extract the entire span as a number of milliseconds. 将整个范围提取为毫秒数。

long millisSinceStartOfDay = d.toMillis() ;

Beware of data loss. 注意数据丢失。 The java.time classes have resolution of nanoseconds, so you are ignoring the finer parts of the value if present when you call the to… methods. java.time类的分辨率为纳秒,因此当您调用to…方法时,如果存在,则忽略值的更精细部分。


About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧遗留日期时间类,如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参阅Oracle教程 And search Stack Overflow for many examples and explanations. 并搜索Stack Overflow以获取许多示例和解释。 Specification is JSR 310 . 规范是JSR 310

You may exchange java.time objects directly with your database. 您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later. 使用符合JDBC 4.2或更高版本的JDBC驱动程序 No need for strings, no need for java.sql.* classes. 不需要字符串,不需要java.sql.*类。

Where to obtain the java.time classes? 从哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目是未来可能添加到java.time的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

        String date = "2015-07-24T09:39:14.000Z";
        //Now we are getting the time only from the above string.
        String time = date.substring(12, 19); 
        System.out.println("Time is: "+time);
        //Since we cannot convert symbols like":" to long we are removing them.
        String timeInLong = time.replaceAll(":", "");
        System.out.println("Time in long format : "+Long.parseLong(timeInLong));

you can try with the next code, I use the library joda-time 你可以尝试下一个代码,我使用库joda-time

java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf("2015-07-24T09:45:44.000Z"); long dateLong=new DateTime(ts2).toDate().getTime();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM