Java programming language

Date and time

Traditional date management

  

How could we manage a date in a Java program? We could, for instance, store day, month and year as separate integers, or the whole date as a string. However, it would be difficult to validate a date, or to substract dates, for instance. Hopefully, Java provides some classes to deal with dates.

Using Date and Calendar classes

From the very first versions of Java language, we have two classes available to manage dates. These classes are Date and Calendar.

Regarding Date class, it has some methods and constructors to instantiate dates, but most of them are now deprecated. Calendar class replaces Date class when creating dates in Java:

Calendar cal = Calendar.getInstance();
cal.set(2021, 5, 4);
System.out.println(cal.getTime());
// Thu Jun 24 20:09:27 CEST 2021

As you can see, getInstance method from Calendar class lets us instantiate objects of this class, and set method lets us specify a concrete year, month (starting from 0) and day.

We can also create a full date including hour, minute and second. We can also use set method specifying the type of elemento (day, month, hour, minute…) that we are setting:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2021);
cal.set(Calendar.MONTH, Calendar.JUNE);
cal.set(Calendar.DAY_OF_MONTH, 24);
cal.set(Calendar.HOUR, 10);
cal.set(Calendar.AM_PM, Calendar.PM);
// Also: cal.set(Calendar.HOUR_OF_DAY, 22);
cal.set(Calendar.MINUTE, 36);
cal.set(Calendar.SECOND, 54);

System.out.println(cal.getTime());
// Thu Jun 24 22:36:54 CEST 2021

System.out.println(cal.get(Calendar.DAY_OF_MONTH) +
    "/" + (cal.get(Calendar.MONTH) + 1) + "/" +
    cal.get(Calendar.YEAR));
// 24/6/2021

We can also do some basic operations with Calendar objects:

Calendar date1 = Calendar.getInstance();
date1.add(Calendar.DAY_OF_MONTH, 10);
System.out.println("In 10 days it will be " + 
    date1.getTime());

Calendar date2 = Calendar.getInstance();
date2.add(Calendar.DAY_OF_MONTH, -10);
if (date2.before(date1))
    System.out.println("It's before");

However, using Calendar class has some drawbacks or restrictions: we can’t easily format a date in an output, or get the difference between two dates, for instance. So we should better use some newer classes, as we will see in next documents.

Exercise 1:

Create a program called UserBirthday that asks the user to enter his birth date (day, month and year separately), and then tell him if his birthday has already taken place this year or not.