gpt4 book ai didi

Java 日期和日历

转载 作者:行者123 更新时间:2023-11-29 08:26:10 25 4
gpt4 key购买 nike

我知道 Java 8 有一个基于 Joda Time 的大大改进的日期和时间库,但我很好奇旧库中做出的决定。我还没有找到关于 java.util.Date 构造函数弃用基本原理的任何好的解释(我发现的最接近的问题是:Difference between new Date() and Calendar date 但它不询问已弃用的方法/构造函数并且没有被接受的答案)。

构造函数 java.util.Date(year, month, day) 被认为已弃用,我们应该使用 new GregorianCalendar(year + 1900, month, date)。如果我们在 Calendar 实例上调用 getTime()(它返回一个 Date...),除了避免使用已弃用的构造函数之外,我们还获得了什么?甚至 java.sql.Date.toLocalDate 在内部也使用了一些已弃用的方法。

我有一个代码库充斥着这种模式(新的 GregorianCalendar 后跟 getTime),只是为了避免 java.util.Date 的弃用方法(我需要 JPA 和 JDBC 中的 java.util.Date 和 java.sql.Date),但我不确定当时的意义是什么 (*)。

(*) 现在我终于可以将它们全部更改为 LocalDate,因为无论如何这是我真正需要的——保存用户输入的内容而不进行任何时区转换。

最佳答案

参见 java.util.Date 的 javadoc 中的第二段:

Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

因此,要回答“我们获得了什么?”这个问题,答案是“支持国际化”:

  • 能够指定时区(使用 Calendar)。

  • 能够使用非公历(使用 Calendar)。

  • 能够使用日期字符串的本地化格式和解析(使用 DateFormat)。

关于Java 日期和日历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52858579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com