Using the ThreeTen Android Backport library, what is the simplest way to convert a ZonedDateTime
or OffsetDateTime
into an old-school java.util.Date
instance?
If I had full Java 8 libs at my disposal, this of course would be the way to do it (as in this question):
Date.from(zonedDateTime.toInstant());
But I cannot use that on Android; specifically Date.from(Instant instant)
is missing.
now() now() method of a ZonedDateTime class used to obtain the current date-time from the system clock in the default time-zone. This method will return ZonedDateTime based on system clock with default time-zone to obtain the current date-time. The zone and offset will be set based on the time-zone in the clock.
ZonedDateTime describes a date-time with a time zone in the ISO-8601 calendar system (such as 2007-12-03T10:15:30+01:00 Europe/Paris ). OffsetDateTime describes a date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system (such as 2007-12-03T10:15:30+01:00 ).
OffsetDateTime is an immutable representation of a date-time with an offset. This class stores all date and time fields, to a precision of nanoseconds, as well as the offset from UTC/Greenwich. For example, the value "2nd October 2007 at 13:45.30. 123456789 +02:00" can be stored in an OffsetDateTime .
Well, one straightforward way is to get milliseconds since epoch and create the Date from that:
long epochMilli = zonedDateTime.toInstant().toEpochMilli();
Date date = new Date(epochMilli);
Feel free to point out if there's some preferable way.
See DateTimeUtils
which handles the methods added to classes like java.util.Date
:
http://www.threeten.org/threetenbp/apidocs/org/threeten/bp/DateTimeUtils.html
Edit: using that, the complete code would be:
DateTimeUtils.toDate(zonedDateTime.toInstant())
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