我应该使用java.util.Date或者切换到java.time.LocalDate [英] Should I use java.util.Date or switch to java.time.LocalDate

查看:143
本文介绍了我应该使用java.util.Date或者切换到java.time.LocalDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:嗯,显然这个意见太过分了,所以让我试着更准确地说出来 -



使用LocalDate有什么明确的注意事项或缺点,本地时间等在Java代码中不需要任何向后兼容性,如果是的话 - 它们是什么?



我正在寻找Current EE libraries X和Y不能与LocalDate正常工作或这个非常有用的模式被打破了LocalTime等等。






(这是原始的问题供参考)



对于Java 8,引入了一个新的时间API,即java.time.LocalDate等,但java.util。日期未被标记为已弃用。



我正在撰写一个新项目,不需要向后兼容。我应该只使用LocalDate,LocalDateTime等吗?有没有使用这个新的API,而不是好的旧的java.util.Date?



特别是 - 我将主要使用JDBC工作。从我看到的JDBC处理java.util.Date很好。它是否适合LocalDate?



搜索产生了大量的网站,告诉如何从一种格式转换为另一种格式,但没有明确的答案,如果新的代码使用旧的API。



谢谢。

解决方案

.util.Date可用于存储日期和时间(它存储UTC时间从UTC以来毫秒的偏移量)



由于更大的功能,我一定会使用新的API: / p>


  • 更容易的格式/解析。 API有自己的格式/解析方法

  • API包含加减法操作(减号,加上等等)



以上都没有可用java.util.Date



旧日期也可以转换为LocalDateTime,如下所示:

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


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.

解决方案

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

这篇关于我应该使用java.util.Date或者切换到java.time.LocalDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆