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?
The difference between Date and Calendar is that Date class operates with specific instant in time and Calendar operates with difference between two dates. The Calendar class gives you possibility for converting between a specific instant in time and a set of calendar fields such as HOUR, YEAR, MONTH, DAY_OF_MONTH.
Date has some serious design flows, from the day it was introduced. Many of its methods were deprecated since Java 1.1 and ported to (abstract) java.
The standard alternate is using the Calendar Object. Calendar has one dangerous point (for the unwary) and that is the after / before methods. They take an Object but will only handle Calendar Objects correctly. Be sure to read the Javadoc for these methods closely before using them.
Date and Time APIs in Java 8 are immutable and therefore thread safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With