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?
String of ISO-8601 datetime to number of seconds in Java
2.9k views Asked by yAsH AtThere are 3 answers
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.
try this way
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