How can I change java.util.Date to ISO String using ThreeTenABP

894 Views Asked by At

I'm using ThreeTenABP for converting date time for Android. My question is how can I change a java.util.Date to an ISO String (format is 2018-05-24T02:33:10.062Z) by ThreeTenABP?

3

There are 3 best solutions below

2
On BEST ANSWER

A ThreetenABP-solution can look like this:

java.util.Date d = ...;
org.threeten.bp.Instant instant = org.threeten.bp.DateTimeUtils.toInstant(d);
String iso = instant.toString();

If you wish more control over formatting then you can convert the instant to a ZonedDateTime (or better to an OffsetDateTime) and use a dedicated DateTimeFormatter.

4
On

I do not know about android, but if java.text.SimpleDateFormat is available you could do:

new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(new Date())

0
On

Expression:

new Date().toInstant().toString()

results in

2019-12-31T06:32:37.997Z