Java Date vs Calendar

2019-01-04 04:36发布

Could someone please advise the current "best practice" around Date and Calendar types.

When writing new code, is it best to always favour Calendar over Date, or are there circumstances where Date is the more appropriate datatype?

13条回答
一纸荒年 Trace。
2楼-- · 2019-01-04 05:39

Date is best for storing a date object. It is the persisted one, the Serialized one ...

Calendar is best for manipulating Dates.

Note: we also sometimes favor java.lang.Long over Date, because Date is mutable and therefore not thread-safe. On a Date object, use setTime() and getTime() to switch between the two. For example, a constant Date in the application (examples: the zero 1970/01/01, or an applicative END_OF_TIME that you set to 2099/12/31 ; those are very useful to replace null values as start time and end time, especially when you persist them in the database, as SQL is so peculiar with nulls).

查看更多
登录 后发表回答