Java Date vs Calendar
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?
Date is a simpler class and is mainly there for backward compatibility reasons. If you need to set particular dates or do date arithmetic, use a Calendar. Calendars also handle localization. The previous date manipulation functions of Date have since been deprecated.
Personally I tend to use either time in milliseconds as a long (or Long, as appropriate) or Calendar when there is a choice.
Both Date and Calendar are mutable, which tends to present issues when using either in an API.
The best way for new code (if your policy allows third-party code) is to use the Joda Time library.
Both, Date and Calendar, have so many design problems that neither are good solutions for new code.
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.
上一篇: 如何格式化JavaScript日期
下一篇: Java日期与日历