23

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.

Jonik
  • 77,494
  • 68
  • 254
  • 365

3 Answers3

39

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.

Jonik
  • 77,494
  • 68
  • 254
  • 365
18

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())
Jonik
  • 77,494
  • 68
  • 254
  • 365
JodaStephen
  • 57,570
  • 15
  • 91
  • 113
  • 3
    Nice, this utility class is what I had missed. So the exact code would be `DateTimeUtils.toDate(zonedDateTime.toInstant())`. Also good to note (looking at ThreeTenABP sources) that under the hood it uses just [what I had thought](http://stackoverflow.com/a/41480812/56285), i.e. `new Date(instant.toEpochMilli())`. – Jonik Jan 09 '17 at 10:36
0
 Date.from(zonedDateTime.toInstant())
Sten
  • 162
  • 7