I am trying to convert a valid ISO 8601 string to a consistent format so that sort and search using simple lexicographical order is possible.
My application could receive a date/time in any of the following formats, for example:
2015-02-05T02:05:17.000+00:00
2015-02-05T02:05:17+00:00
2015-02-05T02:05:17Z
These all represent the same date/time and I would like to convert them all to a canonical form for storage, say:
2015-02-05T02:05:17.000Z
My first thought was to just parse them using a technique from Converting ISO 8601-compliant String to java.util.Date, and then convert back to the desired string, but this breaks down when dealing with less precise date/times, for example:
2015-02-05T02:05:17Z
2015-02-05T02:05Z
2015-02-05Z
2015-02Z
2015Z
The imprecision of these times should be preserved. They should not be converted to:
2015-02-05T00:00:00.000Z
I've looked Java 8 and Joda-Time, but they seem to want to treat everything as specific points in time, and can't model the imprecise nature or partial dates/times.
UPDATE:
Using Java 8, I can do:
OffsetDateTime dateTime = OffsetDateTime.parse("2015-02-05T02:05:17+00:00");
System.out.println(dateTime.toString());
which gives me:
2015-02-05T02:05:17Z
which is what I want, but:
OffsetDateTime dateTime = OffsetDateTime.parse("2015-02-05T02:05:17.000+00:00");
System.out.println(dateTime.toString());
also gives me:
2015-02-05T02:05:17Z
Notice that java has thrown away the millisecond precision. Specifying 000 is treated the same as not specifying anything, which doesn't seem quite right.
No comments:
Post a Comment