I have a string for date time coming as like this without any spaces in between them:
TueDec2618:47:09UTC2017
Is there any way to convert this to unix timestamps? The date time string will always be in that format.
I have a string for date time coming as like this without any spaces in between them:
TueDec2618:47:09UTC2017
Is there any way to convert this to unix timestamps? The date time string will always be in that format.
The comment by ernest_k is well thought out and solves your issue:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("EEEMMMddHH:mm:sszyyyy", Locale.ENGLISH);
String dateTimeString = "TueDec2618:47:09UTC2017";
ZonedDateTime dateTime = ZonedDateTime.parse(dateTimeString, formatter);
long unixTimestamp = dateTime.toEpochSecond();
System.out.println("Parsed date-time " + dateTime + " Unix timestamp " + unixTimestamp);
The output from running on ThreeTen Backport 1.3.6, tested on Java 1.7.0_79, is:
Parsed date-time 2017-12-26T18:47:09Z[Zulu] Unix timestamp 1514314029
I am still on Java 7 btw so can't use
ZonedDataTime
andDateTimeFormatter
but I can use joda library.
Indeed you can. java.time just requires at least Java 6.
org.threeten.bp
with subpackages.While Joda-Time would be another nice solution, I believe that you should prefer the ThreeTen Backport over Joda-Time (though opinions differ). The Joda-Time home page advises:
Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to
java.time
(JSR-310).
So java.time seems to be the future-proof solution.
java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).