Java - Calendar Util (Date)

> Procedural Languages > Java > Java - Date / Time

1 - About

The java.util.Calendar is one of the Java implementation that represents time.

A calendar = a day in a calendar

The java.util.Calendar class provides methods:

  • a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on
  • methods for converting between a specific instant in time
  • methods for manipulating the calendar fields, such as getting the date of the next week.

An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).

Advertising

3 - Initialisation

3.1 - Now

Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time:

Calendar rightNow = Calendar.getInstance();

3.2 - Specific Instant

Calendar calendar = Calendar.getInstance();
calendar.set(2015,Calendar.APRIL,12,0,0,0); // You can also use a month number but it's 0 based. 0=January
Date myDate = calendar.getTime();

3.3 - Date

Calendar cal = Calendar.getInstance();
cal.setTime(date);

4 - Constant

  • YEAR, MONTH,
  • DAY_OF_MONTH: 1 31
  • DAY_OF_WEEK: 1 7 of MONDAY … SUNDAY

5 - Management

5.1 - From Date to LocalDate and formatter

The Date function are deprecated. We need to path through the Calendar to initialize a LocalDate which is part of the new java time framework.

Date actualDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(actualDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
LocalDate localDate = LocalDate.of(year,month,day);
sout(localDate.format(DateTimeFormatter.ISO_DATE));

Java - LocalDate

Advertising

5.2 - Next Monday

Calendar rightNow = Calendar.getInstance();
rightNow.add(Calendar.DAY_OF_MONTH,7);
rightNow.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
Date nextMonday = rightNow.getTime();