Java - Calendar

About

The java.util.Calendar is a class that wraps a instant in time and offers utility function that manipulate time.

ie a calendar = = one date object = a day in a calendar

Structure

The java.util.Calendar class provides:

Management

Set

  • 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();
  • Specific Instant
Calendar calendar = Calendar.getInstance();
// set
calendar.set(2015,Calendar.APRIL,12,0,0,0); // You can also use a month number but it's 0 based. 0=January
// or
Date actualDate = new Date();
calendar.setTime(actualDate);
// or set the next day
calendar.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);

Conversion

toDate

Date myDate = calendar.getTime();

Add

  • Add 7 days
Calendar rightNow = Calendar.getInstance();
rightNow.add(Calendar.DAY_OF_MONTH,7);

How to

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

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();

Powered by ComboStrap