I. Introduction of Calendar class

In Java, time classes mainly include Date and Calendar. Java officially recommends using Calendar to replace Date. There can be free conversion between Calendar and Date, and the link of conversion is time. The java.util.Calendar class is an abstract class that provides methods for converting between a specific time and a set of Calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, as well as methods for manipulating Calendar fields, such as getting next week’s date. A moment can be represented by a millisecond value, which is the offset from the epoch (00:00:00.000 GMT, January 1, 1970, Gregorian calendar).

Constants in the Calendar class

The field values meaning
public final static int ERA = 0;
public final static int YEAR = 1; By default, the indication is year
public final static int MONTH = 2; Month (starting from 0, the 12 months of the year are represented by 0 to 11)
public final static int WEEK_OF_YEAR = 3; The current time is the week of the current year (calendar week)
public final static int WEEK_OF_MONTH = 4; The current time is the week of the current month (calendar week)
public final static int DATE = 5; The day of a month
public final static int DAY_OF_MONTH = 5; The day of a month
public final static int DAY_OF_YEAR = 6; The day of the year
public final static int DAY_OF_WEEK = 7; The number of days in a week (Sunday to Saturday) is 1-7.
public final static int DAY_OF_WEEK_IN_MONTH = 8; The current time is the week of the current month

Based on the number of days in a month, the first day of a month is the first week, and the eighth day is the second week
public final static int AM_PM = 9; Check whether the current time is AM or PM. If AM returns 0, and if PM returns 1
public final static int HOUR = 10; Hours (12 hours)
public final static int HOUR_OF_DAY = 11; Hours (24 hours)
public final static int MINUTE = 12; points
public final static int SECOND = 13; seconds
public final static int MILLISECOND = 14; ms
public final static int ZONE_OFFSET = 15;
public final static int DST_OFFSET = 16;
public final static int FIELD_COUNT = 17;
public final static int SUNDAY = 1; Sunday
public final static int MONDAY = 2; Monday
public final static int TUESDAY = 3; Tuesday
public final static int WEDNESDAY = 4; Wednesday
public final static int THURSDAY = 5; Thursday
public final static int FRIDAY = 6; Friday
public final static int SATURDAY = 7; Saturday
public final static int JANUARY = 0;
public final static int FEBRUARY = 1;
public final static int MARCH = 2;
public final static int APRIL = 3;
public final static int MAY = 4;
public final static int JUNE = 5;
public final static int JULY = 6;
public final static int AUGUST = 7;
public final static int SEPTEMBER = 8;
public final static int OCTOBER = 9;
public final static int NOVEMBER = 10;
public final static int DECEMBER = 11;
public final static int UNDECIMBER = 12;
public final static int AM = 0; In the morning
public final static int PM = 1; In the afternoon

Common methods of Calendar class

3.1 Constructors

Because the Decorator of the Calendar class is protected, this object cannot be created directly; it needs to be created using a static method that returns a subclass object.

// Get a calendar with the default time zone and locale
public static synchronized Calendar getInstance(a)
// Get a calendar with the given time zone and default locale
public static synchronized Calendar getInstance(TimeZone zone)
// Get a calendar with the default time zone and given locale
public static synchronized Calendar getInstance(Locale aLocale)
// Get a calendar with the given time zone and locale
public static synchronized Calendar getInstance(TimeZone zone, Locale aLocale)
Copy the code

3.2 set values

methods instructions
public final void set(int field, int value) Sets the time domain with the given value
public final void set(int year,int month,int date) Set the values for the year, month, and date fields.

Year – Sets the value of the year time domain.

Month – Sets the value of the month time domain, starting from 0

Date – Sets the value of the date time field.
public final void set(int year,int month,int date,int hour,int minute) Set the year, month, date, hour, and minute values.

Year – Sets the value of the year time domain.

Month – Sets the value of the month time domain, starting from 0

Date – Sets the value of the date time field.

Hour – Sets the value of the hour time domain.

Minute – Sets the value of the minute time domain.
public final void set(int year,int month,int date,int hour,int minute,int second) Set the year, month, date, hour, and minute values.

Year – Sets the value of the year time domain.

Month – Sets the value of the month time domain, starting from 0

Date – Sets the value of the date time field.

Hour – Sets the value of the hour time domain.

Minute – Sets the value of the minute time domain.

Second – Sets the value of the second time field
public final void setTime(Date date) Sets the current time of Calendar with the given Date
protected void setTimeInMillis(long millis) Sets the current time of Calendar with the given long integer
public void setTimeZone(TimeZone value) Sets the time zone with the given time zone value

Get the value 3.3

methods instructions
public final int get(int field) Gets the value of the given time domain
public static synchronized Locale[] getAvailableLocales() Get a collection of leashes to install Calendars
public final Date getTime() Gets the current time of the calendar
protected long getTimeInMillis() The current time, as the UTC millisecond value from the start time
public final void clear() Clear all time domain values to zero
public final void clear(int field) Clears the value of the given time domain
public int getFirstDayOfWeek() Get the first day of the week

3.4 compare the value

  • Compares the time values represented by two Calendar objects, and returns a value of 0 if the time represented by the parameter is equal to the time represented by this Calendar;
  • Returns a value less than 0 if the Calendar time is before the time represented by the parameter;
  • If the time of this Calendar is after the time indicated by the parameter, a value greater than 0 is returned.
methods instructions
public abstract boolean equals(Object obj) Compares the calendar with the specified object
public abstract boolean before(Object when) True if the Calendar date object precedes the time of WHEN; Otherwise, it is false.
public abstract boolean after(Object when) True if the Calendar date object is after the time of WHEN; Otherwise, it is false.
public abstract void add(int field,int amount) Adds or subtracts the specified amount of time to the current Calendar date object
private int compareTo(long t) Compares the time values represented by two Calendar objects.

If the time represented by the argument is equal to the time represented by this Calendar, a value of 0 is returned;

Returns a value less than 0 if the Calendar time is before the time represented by the parameter;

If the time of this Calendar is after the time indicated by the parameter, a value greater than 0 is returned.

3.5 calculated value

methods instructions
public int getActualMaximum(int field) Gets the actual maximum value that a given time domain can have
public int getActualMinimum(int field) Gets the actual minimum that a given time domain can have
public abstract int getMinimum(int field) Get the minimum value of the given time domain
public abstract int getMaximum(int field) Gets the maximum value of the given time domain

Four, the instance,

  • Basic example
    public class WorkCalendarHelper {
    
        private final static String[] WEEKS = {"Monday"."Tuesday"."Wednesday"."Thursday"."Friday"."Saturday"."Sunday"};
    
        public static void main(String[] args) {
            // Get an instance of Calendar using Calendar getInstance()
            Calendar calendar = Calendar.getInstance();
            // Initialize the Calendar object, but it is not necessary unless you need to reset the time
            calendar.setTime(new Date());
            // Get the time value
            System.out.println(calendar.getTime());
            // Displays the year
            System.out.println("The year is:" + calendar.get(Calendar.YEAR));
    
            // Displays the month (Calendar month starts from 0, that is, the 12 months of the year are represented by 0 to 11.)
            System.out.println("Month is:" + (calendar.get(Calendar.MONTH) + 1));
            / /,
            System.out.println("Date:" + calendar.get(Calendar.DATE));
            / / week
            System.out.println("For the week:" + WEEKS[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
            //
            System.out.println("Date:" + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
            // the NTH day of a month
            System.out.println("The first of the month" + calendar.get(Calendar.DAY_OF_MONTH) + "Day");
            // The NTH day of the year
            System.out.println("Number one of the year" + calendar.get(Calendar.DAY_OF_YEAR) + "Day");
    
            // get morning and afternoon
            System.out.println(calendar.get(Calendar.AM_PM) == 0 ? "Morning" : "Afternoon");
            / /
            System.out.println("When:" + calendar.get(Calendar.HOUR));
            // The default value is 24 hours
            System.out.println("When:" + calendar.get(Calendar.HOUR_OF_DAY));
            / / points
            System.out.println("Minutes are:" + calendar.get(Calendar.MINUTE));
            / / SEC.
            System.out.println("Seconds are:" + calendar.get(Calendar.SECOND));
            / / ms
            System.out.println("Milliseconds are:" + calendar.get(Calendar.MILLISECOND));
            System.out.println("Week of month:" + calendar.get(Calendar.WEEK_OF_MONTH));
            System.out.println("Weeks of the year:" + calendar.get(Calendar.WEEK_OF_YEAR));
            System.out.println("The calendar type is:" + calendar.get(Calendar.ERA));
            System.out.println("Zone for."+ calendar.get(Calendar.ZONE_OFFSET)); }}Copy the code
  • Gets all dates for a year
    public static List<Map<String,Object>> initCalendar(int year) {
        List<Map<String,Object>> resultList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        int monthSum = 12;
        for (int i = 0; i < monthSum; i++) {
            calendar.set(year, i, 1);
            // Obtain the minimum number of days in a month
            int monthMin = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
            // Obtain the maximum number of days in a month
            int monthMax = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    
            Map<String,Object> workCalendar;
            String timeCode;
            for (int day = monthMin; day <= monthMax; day++) {
                workCalendar = new HashMap<String,Object>(4);
                calendar.set(year, i, day);
                if ((calendar.get(7) = =1) || (calendar.get(7) = =7)) {
                    timeCode = "sys_weekend";
                } else {
                    timeCode = "sys_workday";
                }
                // Work time code
                workCalendar.put("timeCode",timeCode);
                / / year
                workCalendar.put("year",year);
                / / in
                workCalendar.put("month",(i+1));
                / / day
                workCalendar.put("day",day); resultList.add(workCalendar); }}return resultList;
    }
    Copy the code
  • Gets all the dates of the current month
    /** * gets all the dates of the current month */
    public static List<Map<String, Object>> currentMonthDay() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        // Create a calendar
        Calendar ca = Calendar.getInstance();
        // Set the time
        ca.setTime(new Date());
        // Adjust the time to the last day of the current calendar month
        ca.set(ca.get(Calendar.YEAR), ca.get(Calendar.MONTH) + 1.0);
        // Get the actual total number of days in the current calendar month
        int dayNumOfMonth = ca.get(Calendar.DAY_OF_MONTH);
        // Point the calendar time to the first of the current calendar month
        ca.set(Calendar.DAY_OF_MONTH, 1);
        Map<String, Object> workCalendar;
        String timeCode;
        for (int i = 0; i < dayNumOfMonth; i++, ca.add(Calendar.DATE, 1)) {
            workCalendar = new HashMap<String, Object>(4);
            // Set to 0 hours, 0 minutes, 0 seconds, 0 milliseconds
            ca.set(Calendar.HOUR_OF_DAY, 0);
            ca.set(Calendar.MINUTE, 0);
            ca.set(Calendar.SECOND, 0);
            ca.set(Calendar.MILLISECOND, 0);
            if ((ca.get(7) = =1) || (ca.get(7) = =7)) {
                timeCode = "sys_weekend";
            } else {
                timeCode = "sys_workday";
            }
            // Work time code
            workCalendar.put("timeCode", timeCode);
            / / year
            workCalendar.put("year", ca.get(Calendar.YEAR));
            / / in
            workCalendar.put("month", (ca.get(Calendar.MONTH) + 1));
            / / day
            workCalendar.put("day", ca.get(Calendar.DAY_OF_MONTH));
            resultList.add(workCalendar);
        }
        return resultList;
    }
    Copy the code
  • Gets all the dates of the current week
    /** * get all the dates of the week, sorted by time */
    public static List<Map<String, Object>> currentMeekDay() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        // Create a calendar
        Calendar ca = Calendar.getInstance();
        // Set the time
        ca.setTime(new Date());
        // Set Monday to the first day of the week
        ca.setFirstDayOfWeek(Calendar.MONDAY);
        // Point the Calendar date object to the Monday of the week
        ca.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        Map<String, Object> workCalendar;
        String timeCode;
        for (int i = 0; i < 7; i++, ca.add(Calendar.DATE, 1)) {
            workCalendar = new HashMap<String, Object>(4);
            // Set the calendar time to 0 hours 0 minutes 0 seconds
            ca.set(Calendar.HOUR_OF_DAY, 0);
            ca.set(Calendar.MINUTE, 0);
            ca.set(Calendar.SECOND, 0);
            ca.set(Calendar.MILLISECOND, 0);
            // Add time to list
            if ((ca.get(7) = =1) || (ca.get(7) = =7)) {
                timeCode = "sys_weekend";
            } else {
                timeCode = "sys_workday";
            }
            // Work time code
            workCalendar.put("timeCode", timeCode);
            / / year
            workCalendar.put("year", ca.get(Calendar.YEAR));
            / / in
            workCalendar.put("month", (ca.get(Calendar.MONTH) + 1));
            / / day
            workCalendar.put("day", ca.get(Calendar.DAY_OF_MONTH));
            resultList.add(workCalendar);
        }
        return resultList;
    }
    Copy the code