Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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

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?

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top