Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

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

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 a 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 is 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 as well suited for LocalDate?

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

Thanks.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...