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
Articles Related
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.)
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
- return a date
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));
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();