有人能建议当前的“最佳实践”围绕日期和日历类型。

在编写新代码时,最好总是使用Calendar而不是Date,还是在某些情况下Date是更合适的数据类型?


当前回答

Date最适合存储日期对象。它是持久化的,序列化的…

日历是操作日期的最佳工具。

注意:我们有时也更喜欢java.lang.Long而不是Date,因为Date是可变的,因此不是线程安全的。在Date对象上,使用setTime()和getTime()在两者之间切换。例如,应用程序中的一个常量Date(例如:0 1970/01/01,或应用程序的END_OF_TIME,您设置为2099/12/31;这些对于替换null值作为开始时间和结束时间非常有用,特别是当您在数据库中持久化它们时,因为SQL对null非常特殊)。

其他回答

Date and Calendar are really the same fundamental concept (both represent an instant in time and are wrappers around an underlying long value). One could argue that Calendar is actually even more broken than Date is, as it seems to offer concrete facts about things like day of the week and time of day, whereas if you change its timeZone property, the concrete turns into blancmange! Neither objects are really useful as a store of year-month-day or time-of-day for this reason. Use Calendar only as a calculator which, when given Date and TimeZone objects, will do calculations for you. Avoid its use for property typing in an application. Use SimpleDateFormat together with TimeZone and Date to generate display Strings. If you're feeling adventurous use Joda-Time, although it is unnecessarily complicated IMHO and is soon to be superceded by the JSR-310 date API in any event. I have answered before that it is not difficult to roll your own YearMonthDay class, which uses Calendar under the hood for date calculations. I was downvoted for the suggestion but I still believe it is a valid one because Joda-Time (and JSR-310) are really so over-complicated for most use-cases.

我一直提倡joda时间。这是为什么。

API是一致的和直观的。不像java.util。日期/日历api 它没有线程问题,不像java.text.SimpleDateFormat等(我见过许多客户端问题,没有意识到标准日期/时间格式不是线程安全的) 它是新的Java日期/时间api (JSR310,计划在Java 8中发布)的基础。因此,您将使用的api将成为核心Java api。

编辑:如果可以迁移到Java 8, Java 8引入的Java日期/时间类现在是首选的解决方案

日期应该用作不可变的时间点;日历是可变的,如果您需要与其他类协作以得出最终日期,则可以传递和修改日历。把它们看作类似于String和StringBuilder,您就会理解我认为应该如何使用它们。

(是的,我知道Date实际上在技术上不是不可变的,但目的是它不应该是不可变的,如果没有调用已弃用的方法,那么它就是不可变的。)

对于新代码(如果您的策略允许第三方代码),最好的方法是使用Joda Time库。

日期和日历都有很多设计问题,它们都不是新代码的好解决方案。

有点晚了,但是Java在JDK 8中有一个新的日期时间API。您可能希望升级JDK版本并采用该标准。没有更多凌乱的日期/日历,没有更多第三方罐子。