10

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!

Leem.fin
  • 40,781
  • 83
  • 202
  • 354
  • 2
    What happens when you try? Hint: a Date doesn't have any timezone, whatever the way you get its instance. Other hint: the current instant is the current instant, whatever the timezone is. – JB Nizet Dec 19 '13 at 22:46
  • 2
    Date/Calendar are confusing because they are poorly designed and implemented classes. Save yourself the headache, avoid those classes and use a decent library instead: Either (a) [Joda-Time](http://www.joda.org/joda-time/) or (b) the new [JSR 310: Date and Time API](https://www.jcp.org/en/jsr/detail?id=310) java.time.* classes bundled with Java 8 and supplanting the java.util.Date/Calendar mess. – Basil Bourque Dec 20 '13 at 01:23
  • For new readers to the question, don’t use `Date` nor `Calendar` nor `SimpleDateFormat`, just as jumping_monkey also says in their answer. They are all confusingly and poorly designed and are all long outdated. There are a number of misunderstandings in the question exactly because the classes are so confusing. `LocalDate.now(ZoneId.systemDefault()).toString()` will give you the result you are after. [Oracle Tutorial: Date Time](https://docs.oracle.com/javase/tutorial/datetime/index.html) shows you how to use the modern classes. – Ole V.V. Mar 24 '22 at 13:57
  • And just to add to the contusion, there are probably special cases where the two methods in the question will not give the same result. – Ole V.V. Mar 24 '22 at 18:32

3 Answers3

12

Practical info about Java Calendar and Date

If you want to operate with different dates in your Java program you will use Java Calendar class.

I will try to give you some overview of not widely known facts about Java Calendar and Date classes, working code examples, which you can try right away.

The basic information about Calendar class is provided by Java API. The Calendar class is about days, months and years. One could ask: is not Date class about the same? Not exactly...

What is difference between Java Date and Calendar classes?

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. You can also manipulate with the calendar fields, for example getting the date of your grandmother birthday :).

I would like to point some things about Calendar and Date which you should know and which are not obvious...

Leap seconds.

Years, months, dates and hours are in "normal" range like:

A year y - 1900. A month from 0 to 11 A date (day of month) from 1 to 31 in the usual manner. calendar leap seconds An hour 0 to 23. A minute from 0 to 59 in the usual manner. But, attention!! A second is represented by an integer from 0 to 61. Looks strange - 61 second, but do not forget about leap second. About once every year or two there is an extra second, called a "leap second." The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second.

Lenient fields.

Another funny feature is lenient and non-lenient fields in calendar. What is that? Example:

32 January 2006. Actually if you set your calendar lenient it will be 1 February 2006 and no problem for your program :). If it is non-lenient ArrayIndexOutOfBoundsException exception will be thrown.

Another question is 00:00 end or beginning of day? Is 00:00 A.M. or P.M.? Are midnight and noon A.M. or P.M?

Answer: 23:59 is the last minute of the day and 00:00 is the first minute of the next day. Midnight belongs to "am", and noon belongs to "pm", so on the same day, 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm.

And probably last question: what is epoch? and why this Epoch since January 1, 1970 00:00:00.000 GMT.

Actually it is Unix time, or POSIX time, is a system for describing points in time: it is the number of seconds after 00:00:00 UTC, January 1, 1970.

Wait, one question more!

"If we use the time which is counted since Epoch, how can I know which years had leap seconds and which not?"

Answer: To make life easier leap seconds are not counted. Java Date class takes actual time from OS and most of modern computers can not use leap seconds, their's internal clocks are not so precised. That's why periodical time synchronization is required.

jimagic
  • 4,045
  • 2
  • 28
  • 49
  • 1
    Just a correction about leap seconds. The second can never accept the value 61 - this was an old mistake of an early posix version, meanwhile corrected. Otherwise the difference between UT1 and UTC could be more than 0.9s which is not allowed in UTC norm. This error is still existing in javadoc of java.util.Date, unfortunately. – Meno Hochschild Dec 20 '13 at 11:00
2

There is no difference between at all between those two dates. (The second one is of course a bit wasteful in allocating a Calendar object that you don't use.)

An instance of java.util.Date is an absolute point in time. It has no knowledge of time zones. Setting the Default timezone on the SimpleDateFormat similarly does nothing, it uses the default by.... default!

To try to explain in different terms, the java.util.Date for

10:49 pm Dec 19, 2013 UTC

And

5:49 pm Dec 19, 2013 US Eastern Time

Is exactly the same object. The exact same java.util.Date represents both of those human-readable representations of time. The human-readable considerations only come into play when you use the formatter to turn it back and forth. (Hence why you set the timezone on the formatter, not on the date, date has no knowledge of what a timezone means.)

Affe
  • 47,174
  • 11
  • 83
  • 83
  • If I change my computer's timezone, isn't it so that setting default timezone on SimpleDateFormat will change something for the end result (because default timezone is changed)? – Leem.fin Dec 19 '13 at 22:51
  • Sure, changing your computer's timezone may change the output, but it doesn't matter that you called that function, because SimpleDateFormat was going to use the default anyway. – Affe Dec 19 '13 at 22:53
1

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

jumping_monkey
  • 5,941
  • 2
  • 43
  • 58