I have a date string
String s = "2014-09-01T19:22:43.000Z";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(s);
But I get an exception:
Exception in thread "main" java.text.ParseException: Unparseable date: "2014-09-01T19:22:43.000Z"
How do I convert the above string to unix timestamp? Thanks
How do I convert the above string to unix timestamp?
Instant.parse( "2014-09-01T19:22:43.000Z" )
.getEpochSecond()
The java.time.Instant
class can parse your input string with its standard ISO 8601 format. No need to specify a formatting pattern.
Instant instant = Instant.parse( "2014-09-01T19:22:43.000Z" );
To get a count of milliseconds since the epoch of 1970:
long millisecondsSinceUnixEpoch = instant.toEpochMilli() ;
For whole seconds since epoch of 1970-01-01T00:00:00Z:
long secondsSinceUnixEpoch = instant.getEpochSecond() ;
Be aware of possible data loss when going to milliseconds or whole seconds. The java.time classes have nanosecond resolution, so any microseconds or nanoseconds present in the value will be truncated.
Update The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.
The Joda-Time library makes this work easier. Your ISO 8601 compliant string can be fed directly to a Joda-Time constructor. The built-in parser expects ISO 8601.
DateTime dateTime = new DateTime( "2014-09-01T19:22:43.000Z" ) ;
What do you mean by a Unix timestamp? Some people mean a count of whole seconds since the first moment of 1970 UTC (the Unix epoch) while ignoring leap seconds (see Unix Time). Some people mean a count of milliseconds or other resolution.
Note the use of a long
primitive rather than the more common int
.
For milliseconds, call getMillis()
.
long millisecondsSinceUnixEpoch = dateTime.getMillis();
For whole seconds, divide by 1,000. Consider if you want rounding or truncation of the fractional seconds.
Normally I would suggest passing a DateTimeZone object along with your string to the DateTime constructor. But no need if all you want is a count since epoch.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With