0

joda.time.DateTime.now().toDate()

Why doesn't java.time. offer such a method? What is the best way of converting a java.time.LocalDateTime to java.util.date?

I know I could do as follows, but it doesn't feel right.

 java.time.LocalDateTime date;
 java.util.Date.from(date.atZone(ZoneId.systemDefault()).toInstant());

I'm asking because a java.util.Date is still used in lots of systems, like database mappings for postgres via hibernate.

membersound
  • 66,525
  • 139
  • 452
  • 886
  • 2
    A [`LocalDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html) is not a time as such. It's a zoneless date (such as 12 May 2016 13:45), it is impossible to evaluate it as a time since the epoch without a timezone. Hence your solution, I reckon, is the neatest if you need a `Date`. A [`DateTime`](http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html) is a rather different thing... – Boris the Spider Aug 16 '16 at 12:51

1 Answers1

5

The java.time.* JSR-310 packages do not contain any references to java.util.Date or Calendar. This will allow the old types to be deprecated and removed in the future.

Converting between the old and new forms is possible as seen in these answers. Converting "local" date-times to "instants" is always tricky, and too many helper methods can obscure the important details of the conversion.

Community
  • 1
  • 1
JodaStephen
  • 53,561
  • 13
  • 87
  • 108