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

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

问题描述

嗯,显然它过于基于意见,所以让我试着更准确地改写它 -

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

在不需要任何向后兼容性的 Java 代码中使用 LocalDate、LocalTime 等是否有任何明确的警告或缺点,如果是,它们是什么?

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?

我正在寻找诸如当前的 EE 库 X 和 Y 不能与 LocalDate 一起正常工作"或这个非常有用的模式被 LocalTime 破坏"等内容.

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)

Java 8 引入了新的时间 API,即 java.time.LocalDate 等,但 java.util.Date 未标记为已弃用.

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

我正在编写一个不需要向后兼容的新项目.我应该只使用 LocalDate、LocalDateTime 等吗?与旧的 java.util.Date 相比,使用这个新 API 有什么缺点吗?

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?

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

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?

搜索产生了许多网站,它们告诉我们如何从一种格式转换为另一种格式,但没有明确回答新代码是否应该使用旧 API.

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.

谢谢.

推荐答案

尽管名称如此,java.util.Date 可用于存储日期和时间(它存储自纪元以来的 UTC 毫秒偏移量)

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

我肯定会使用新的 API,因为功能更强大:

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

  • 更容易格式化/解析.API 有自己的格式/解析方法
  • API 包含加减运算(minusMinutesplusDays 等)

以上都不适用于 java.util.Date

Old Date 也可以像这样转换成 LocalDateTime:

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天全站免登陆