Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
Marty Pitt Avatar asked Sep 10 '09 09:09

Marty Pitt


People also ask

What is the difference between Calendar and date in Java?

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.

Is Java date deprecated?

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.

What can I use instead of a Calendar in 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.

Is Java Calendar immutable?

Date and Time APIs in Java 8 are immutable and therefore thread safe.


1 Answers

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.

like image 173
cletus Avatar answered Sep 24 '22 04:09

cletus