Should I use java.util.Date or switch to java.time.LocalDate? Ask Question

Should I use java.util.Date or switch to java.time.LocalDate? Ask Question

Edit: Well, apparently it was too opinion based, so let me try to reword it more precisely -

Are there any clear caveats or drawbacks of using LocalDate, LocalTime etc. in Java code that does not need any backwards compatibility, and if so - what are they?

I'm looking for things like "Current EE libraries X and Y don't work correctly with LocalDate" or "This very useful pattern is broken with LocalTime" et cetera.


(here is the original question for reference)

With Java 8, a new time API was introduced, namely the java.time.LocalDate etc., but java.util.Date is not marked as deprecated.

I am writing a new project, which does not need to be backwards compatible. Should I only use LocalDate, LocalDateTime etc.? Are there any drawbacks to using this new API as opposed to the good old java.util.Date?

In particular - I am going to be working mainly with JDBC. From what I have seen JDBC handles java.util.Date well. Is it also suited for LocalDate?

Searching yielded lots of sites telling how to convert from one format to the other, but no definitive answer as to whether or not new code should use the old API.

ベストアンサー1

Despite the name, java.util.Date can be used to store both date and time (it stores UTC milliseconds offset since epoch)

I would definitely use the new API because of greater features:

  • Easier format/parsing. The API has its own format/parse methods
  • The API includes addition/subtraction operation (minusMinutes, plusDays, etc)

None of above are available on java.util.Date

Old Date can also be converted into LocalDateTime like this:

    Date oldDate = ...
    LocalDateTime newDateTime = 
      LocalDateTime.from(Instant.ofEpochMilli(oldDate.getTime()));

おすすめ記事