Java - Calendar

1 - 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

3 - Structure

The java.util.Calendar class provides:

  • a set of static calendar fields such as:
    • YEAR, MONTH,
    • DAY_OF_MONTH: 1 - 31
    • DAY_OF_WEEK: 1 7 of MONDAY … SUNDAY
    • HOUR, and so on
  • methods to retrieve a:
  • methods for manipulating time (such as getting the date of the next week.)

4 - Management

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

4.2 - Conversion

4.2.1 - toDate


Date myDate = calendar.getTime();

4.3 - Add

  • Add 7 days

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

5 - How to

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

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


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap