String of ISO-8601 datetime to number of seconds in Java

我们两清 提交于 2019-12-25 08:54:03

问题


How do I convert a string of ISO-8601 datetime (ex: 2012-05-31T13:48:04Z) to number of seconds( 10 digit integer) using Java?


回答1:


try this way

String DateStr="2012-05-31T13:48:04Z";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date d=sdf.parse(DateStr);
System.out.println(d.getTime());

output 1338452284000

From the comments of OP getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.Source




回答2:


using SimpleDateFormat and use format like yyyy-MM-dd 'T' HH:mm:ss 'Z'




回答3:


tl;dr

Instant.parse( "2012-05-31T13:48:04Z" )
       .getEpochSecond()

1338472084

See this code run live at IdeOne.com.

Using java.time

Much easier with the java.time classes that supplant the troublesome old legacy date-time classes.

Easy to parse your input string as the java.time classes use ISO 8601 formats by default when generating/parsing strings. So no need to specify a formatting pattern.

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 instant = Instant.parse( "2012-05-31T13:48:04Z" ) ;

I am guessing that by “seconds” you meant the number of seconds elapsed since the beginning of 1970 UTC (1970-01-01T00:00:00Z). The Instant class can tell you the number of seconds since that Unix epoch.

long secondsSinceEpoch = instant.getEpochSecond() ;

1338472084

Beware of data loss, obviously. You are ignoring any fractional second that may be present in your date-time value.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.



来源:https://stackoverflow.com/questions/20322545/string-of-iso-8601-datetime-to-number-of-seconds-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!