Difference between new Date() and Calendar date

Viewed 22842

What is the difference between the two dates below in practice?

  1. Date date = new Date();

  2. Date date = Calendar.getInstance().getTime();

What I understand is that new Date() is a UTC/GMT based date while calendar's getTime() is based on TimeZone & System time. Am I right? Do I miss something still?

Moreover, if my above understanding is correct, can I say that the end results of the following two functions are exactly the same ?

1.

public String getDate1(){
   SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd");
   //I set the time zone & pass the new Date()
   sdf.setTimeZone(TimeZone.getDefault()); 
   return sdf.format(new Date());
}

2.

public String getDate2(){
  SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd");
  //I didn't set the time zone because I think calendar instance will handle timezone change
  return sdf.format(Calendar.getInstance().getTime());
}

I appreciate if you could point out where I understand wrongly & explain to me clearly. Because I feel this thing is confused to me. Thanks!

3 Answers

In 2022, you MUST use java.time classes and you can refer here to know almost everything that needs to be known about time. But if you are using Java versions older than 8, or if you are curious, read on for some high-level overview.

1. Date date = new Date();                       //Thu Mar 24 04:15:37 GMT 2022
2. Date date = Calendar.getInstance().getTime(); //Thu Mar 24 04:15:37 GMT 2022

Date(Does not have a notion of timezone, and is mutable, i.e not thread-safe)

Date is sufficient if you need only a current timestamp in your application, and you do not need to operate on dates, e.g., one-week later. You can further use SimpleDateFormat to control the date/time display format.

Calendar(Abstract class, concrete implementation is GregorianCalendar)

Calendar provides internationalization support. Looking into the source code reveals that: getInstance() returns a GregorianCalendar instance for all locales, (except BuddhistCalendar for Thai ("th_TH") and JapaneseImperialCalendar for Japanese ("ja_JP")).

Trivia

If you look at the Date java documentation, you will see many deprecated methods and the note:As of JDK version 1.1, replaced by Calendar.XXX. This means Calendar was a failed attempt to fix the issues that Date class had. enter image description here

Bonus

You might want to watch this to get some more insights of Date vs Calendar

Related