Calendar

Calendar is an abstract class, and it needs to pass a static method when it is created.


Calendar cal = Calendar.getInstance();

Common method

get: gets the value of the field.
set: sets the value of the specified field.
add: to increase or decrease the calendar
getTime: get the corresponding Date object


get and set methods

import java.util.Calendar;

public class SegmentFault {
    public static void main(String[] args) {

       //  创建Calendar
       Calendar cal = Calendar.getInstance();

       // get

        int year = cal.get(Calendar.YEAR);

        int month = cal.get(Calendar.MONTH);

        int dayOFMonth = cal.get(Calendar.DAY_OF_MONTH);

        System.out.println(year + "年" + month + "月" + dayOFMonth + "日");

        // set

        cal.set(Calendar.YEAR,2020); // 把年更改至 2020
        cal.set(Calendar.MONTH,8);
        cal.set(Calendar.DAY_OF_MONTH,28);
        // 输出一下 
         System.out.print(cal.get(Calendar.YEAR)  + "年" ); // 2020
        System.out.print(cal.get(Calendar.MONTH) + "月" ); // 8
        System.out.println(cal.get(Calendar.DAY_OF_MONTH) + "日"); // 28


  }
}

outputs the result :
July 10, 2021
August 28, 2020 Note : date please follow the time of day form

Note: If you do not add a character string in the first output, add the character.
Reference: Reference Answer


add 、getTime

        // add

        Calendar calendar = Calendar.getInstance();

         // 查看原有日期
        System.out.println(year + "年" + month + "月" + dayOFMonth + "日");

        calendar.add(Calendar.DAY_OF_MONTH,-10);
        calendar.add(Calendar.YEAR,1);

        System.out.print(cal.get(Calendar.YEAR)  + "年" ); // 2020
        System.out.print(cal.get(Calendar.MONTH) + "月" ); // 8
        System.out.println(cal.get(Calendar.DAY_OF_MONTH) + "日"); // 28


        // getTime

        Date date = cal.getTime(); 
        System.out.println(date); 

outputs the result :

July 10, 2021
August 28, 2020
Mon Sep 28 11:32:37 CST 2020


嘻嘻硕
27 声望12 粉丝

想当一只天然呆的鸭qwq