I am assuming you meant without -
and :
. No, your way of parsing into some appropriate date-time object and converting to milliseconds is good and standard, there isn’t really anything better.
Did you intend to use Joda-Time? You may want to think again. The Joda-Time homepage says
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).
JSR-310 is also backported to Java 6 and 7, so I would suggest using that backport in preferrence to Joda-Time.
The following is probably more than you asked for. I suggest a method like:
/**
*
* @param dateTimeString String in 20170609T184237Z format
* @return milliseconds since the epoch as String
* @throws IllegalArgumentException if the String is not in the correct format
*/
private static String isoToEpochMillis(String dateTimeString) {
try {
OffsetDateTime dateTime = OffsetDateTime.parse(dateTimeString,
DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmssX"));
if (! dateTime.getOffset().equals(ZoneOffset.UTC)) {
throw new IllegalArgumentException("Offset is not Z");
}
return String.valueOf(dateTime.toInstant().toEpochMilli());
} catch (DateTimeException dte) {
throw new IllegalArgumentException("String is not in format uuuuMMddTHHmmssZ",
dte);
}
}
Let’s call it like this:
String milliseconds = isoToEpochMillis("20170609T184237Z");
System.out.println(milliseconds);
This prints
1497033757000
I don’t know how strict of a validation you want. Your example string has Z
time zone; As you can see, I am requiring UTC time zone, but will also accept for example 20170609T184237+00
. If that must be Z
, I think you need to use dateTimeString.endsWith("Z")
.