Java Date VS Calendar

Java Date vs Calendar

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.

time vs date vs calendar java

1) Which of this is more "Stable" considering their results? I mean
that it will not have any problem
.

They are both stable and very well tested, especially Calendar which is in the Java API since JDK1.1. Also from the docs of Time:

An alternative to the Calendar and GregorianCalendar classes. An
instance of the Time class represents a moment in time, specified with
second precision. It is modelled after struct tm, and in fact, uses
struct tm to implement most of the functionality.

Time, imho, is much easier to work than Calendar though.

2) Moreover, did they both take into consideration the TimeZone? I
think that the second one does, but what about the calendar?

Yes, they do. You can specify a TimeZone using Calendar.getInstance(java.util.TimeZone). Otherwise, a default one will be used.

3) I tried this code that I have found:

The code works just fine. Make sure you are using new java.util.Date() instead of java.sql.Date, for example.

4) What do you suggest me to use? The only thing I want is a simple
comparison between current month,date,hour with some stored in memory.
(for example if its January 29, display that event. if it is 19.00 am
send notification and so on.)

It's really a matter of personal choice. Using Calendar, for example, to compare if today is January 29, you could simply use the following:

Calendar today = Calendar.getInstance();
int dayOfMonth = today.get(Calendar.DAY_OF_MONTH);
int month = today.get(Calendar.MONTH);
if (month == Calendar.JANUARY && dayOfMonth == 29) {
// January 29
}

Date vs TimeStamp vs calendar?

java.sql.Timestamp A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value.

If you check java.sql.Timestamp JavaDoc, it is very explicit that this class extends from java.util.Date (as java.sql.Date does). And in real world projects you must plain java.util.Date when storing the data in your database and mostly java.sql.Timestamp since it stores date and time value, while java.sql.Date just stores date value.

On the other hand, java.util.Calendar is abstract since there are more implementations of this apart from java.util.GregorianCalendar. If you see the code of Calendar#getInstance from HotSpot, you will see that it calls createCalendar(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT)), and this method code uses 3 different calendars: BuddhistCalendar, JapaneseImperialCalendar and GregorianCalendar. This code is copied from JDK 7 source:

private static Calendar createCalendar(TimeZone zone,
Locale aLocale) {
Calendar cal = null;

String caltype = aLocale.getUnicodeLocaleType("ca");
if (caltype == null) {
// Calendar type is not specified.
// If the specified locale is a Thai locale,
// returns a BuddhistCalendar instance.
if ("th".equals(aLocale.getLanguage())
&& ("TH".equals(aLocale.getCountry()))) {
cal = new BuddhistCalendar(zone, aLocale);
} else {
cal = new GregorianCalendar(zone, aLocale);
}
} else if (caltype.equals("japanese")) {
cal = new JapaneseImperialCalendar(zone, aLocale);
} else if (caltype.equals("buddhist")) {
cal = new BuddhistCalendar(zone, aLocale);
} else {
// Unsupported calendar type.
// Use Gregorian calendar as a fallback.
cal = new GregorianCalendar(zone, aLocale);
}

return cal;
}

Now, why to work directly with Calendar instead of GregorianCalendar? Because you must work with abstract classes and interfaces when provided instead of working directly with implementations. This is better explained here: What does it mean to "program to an interface"?

Apart from this, if you will work with date and times, I recommend using a library like Joda-Time that already handles and solves lot of the problems with the current Java Date API and also provides methods to retrieve this date and times object in java.util.Date flavor.

Java 8 Date API vs Calendar / Date / DateFormat

Should I use it exclusively instead of the old classes?

No, no need to exclude old classes. The old java.util.Date/.Calendar work the same, unchanged. The have not been deprecated.

You can mix and match all three frameworks (old classes, Joda-Time, and java.time). Just be careful of some identical or similar class names -- watch your import statements!

See The Tutorial, Legacy Date-Time Code.

Also, the ThreeTen-Extra project extends java.time with additional features. The "ThreeTen" refers to JSR 310 that defines java.time.

Should I replace existing usages of old classes whereever I spot them because the new stuff is so much better?

If the old code is working as intended, then no need to change now.

If you were concerned about that old code possibly not handling time zones properly or have been wanting to do more localization, the you might want to rework them using java.time. Even then, remember that you can easily convert between j.u.Date and Instant. So you could leave your business logic as-is with j.u.Date/.Calendar and change only the user-presentation code to use java.time.

Should I refrain from using java.util.Calendar, java.util.Date, java.sql.Date and java.text.DateFormat in favor of the new API all together OR are there use cases where the old classes are still preferable?

You will need the old classes for interoperation with old code and libraries that expect the old types. Again, the old classes are not deprecated and are not going away. They will probably never go away given their extensive usage and the Java team’s top priority being preservation of backward-compatibility.

The new java.time classes are far superior, that's why they were added. And they are more logical and easier to use. So yes, it would be beneficial and pleasant to learn how to use them. But not urgent. In a crunch, write code the old way you are used to. When you can afford the time to learn (Tutorial) and to perform extra testing, start to use the new classes.

A newbie programmer should certainly focus their learning on java.time.

Has the Joda Time API become obsolete thanks to the new Date API similarly to the substitution of Guava FluentIterable by Java 8 stream API?

Joda-Time was the inspiration for java.time. The same folks invented both. They intend for java.time to be their "2.0" re-invention of Joda-Time, what they would have done then if they knew what they know now. They have said Joda-Time users should transition over to java.time.

That said, Joda-Time is not going away. It is still worked on, still updated with bug fixes and fresh tz time zone data. And it is very important to the large Android community who have no other decent date-time library (that I know of). So you can continue to rely on Joda-Time, no urgent need to rip out old code, but expect no new features or enhancements.

Joda-Time is well-worn and proven while java.time has had a few minor bugs and kinks to work out. Joda-Time and java.time each have features the other lacks. So personally, I mix-and-match to best fit. I rely on Joda-Time while dabbling with java.time.

Plan an eventual transition to java.time but no rush, no panic.

currentTimeMillis vs Calendar

Calendar is always bad practice.

Java has 3 to 4 APIs for time. In order of introduction:

  • System.currentTimeMillis()
  • (together with the above): java.util.Date and sometime later, java.sql.Timestamp and Date. This is very bad API; at this point, almost all the methods in these are deprecated because they are misleading or straight up do not do what they suggest they do, and are in any case gigantic misnomers. j.u.Date represents an instant in time, not readily representable in human terms. Dates are fundamentally human concepts.
  • Calendar. An attempt to fix the problem. Actually made it worse: The API is misleading and surprising (.set(MONTH, 1) will set the month to.. Februari!), and is entirely non-idiomatic, using .set/.get with an extra parameter with a 'field' concept, and having mutable types). The actual representational power of this API is still limited.
  • JSR310, a.k.a. java.time. THIS is the good one. This has few surprises, is complex where time ends up being actually complex, the types are properly named, going so far as having both j.t.Instant and j.t.ZonedDateTime, and you can express virtually anything date-related.

I'd say using either j.u.Date or Calendar is strongly dis-recommended. If all you're doing is measuring instants in time, feel free to stick with System.currentTimeMillis() - but if ever you need to print that in human form (such as: "On 2020-07-20 at 16:34, this happened"), switch to java.time instead. If you prefer, feel free to ditch currentTimeMillis and use j.t.Instant for those purposes instead - your preference.

What's the difference from Calendar.DATE and Calendar.DAY_OF_MONTH?

See the api doc for java.util.Calendar (emphasis mine):

public static final int DAY_OF_MONTH

Field number for get and set indicating the day of the month. This is a synonym for DATE. The first day of the month has value 1.

“Synonym” means a word with the same meaning.
these two constants mean the same thing and are interchangeable.

Also if you look in the code, you'll notice these constants are defined with the same value:

/**
* Field number for <code>get</code> and <code>set</code> indicating the
* day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
* The first day of the month has value 1.
*
* @see #DAY_OF_MONTH
*/
public final static int DATE = 5;

/**
* Field number for <code>get</code> and <code>set</code> indicating the
* day of the month. This is a synonym for <code>DATE</code>.
* The first day of the month has value 1.
*
* @see #DATE
*/
public final static int DAY_OF_MONTH = 5;


Related Topics



Leave a reply



Submit