Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ZonedDateTime/OffsetDateTime to Date using ThreeTenABP?

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.

like image 785
Jonik Avatar asked Jan 05 '17 08:01

Jonik


People also ask

How do I get the date from ZonedDateTime?

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.

What is the difference between ZonedDateTime and OffsetDateTime?

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 ).

What is OffsetDateTime in Java?

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 .


2 Answers

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.

like image 124
Jonik Avatar answered Oct 14 '22 15:10

Jonik


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())
like image 25
JodaStephen Avatar answered Oct 14 '22 16:10

JodaStephen