The eleventh day of JAVA learning - boxing and unboxing + date class + calendar class use example code

Automatic boxing and unboxing

Boxing: Convert the basic class type to the wrapper class type
Unboxing: Convert the wrapper class type to the basic class type
Autoboxing: Assign the basic type int directly to the wrapper class type Integer
Automatic unboxing: Assign the Integer type directly to int type

Tips:
As long as it is an object, it is best to make a judgment that it is not Null before using it to avoid being a null pointer;

Date class: data, SimpleDataFormat, Calendar

Public Data();
Public Data(long data); long is in milliseconds, and the starting time is 0:00:00 on January 1, 1970. The time here is based on this plus long data ;

Encountered the problem that java.util.data cannot import packages and
has not solved it yet

The time of data output is not conducive to reading, you can use:
SimpleDataFormat

Calendar class

It is an abstract class that can be used for the method of conversion between a certain moment and a group.
Calendar rightNow = Calendar.getInstance();
The get method obtains the value of the Calendar;
add can modify the return value of the Calendar, such as YEAR, MONTH, etc. ;
The set method sets the value in the Calendar;

The month value is calculated from 0, and the difference between the assigned value and the actual value is 1;

The following demonstrates the application:
Code 1:

        public static void main(String[] args) {
    
    
        //获取当前日历时间
            Calendar c = Calendar.getInstance();
//            int year = c.get(Calendar.YEAR);
//            int month = c.get(Calendar.MONDAY)+1;
//            int day = c.get(Calendar.DATE);
//            System.out.println(year+"年"+month+"月");
            c.add(Calendar.YEAR,-3);//对获取的年份-3
            c.set(2020,1,11);//赋值新的日历信息
            //获取对象c中的具体值
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONDAY)+1;
            int day = c.get(Calendar.DATE);
            System.out.println(year+" "+ month +" "+day);

Code 2: Get the number of days in February of any year

   			1、获得年份
            Scanner sc =new Scanner(System.in);
            System.out.println("请输入年份");
            int i = sc.nextInt();
//            2、对象赋值为这一年的3月第一天
            Calendar ca = Calendar.getInstance();
            ca.set(i,2,1);
//            3、对象往前推一天
            ca.add(Calendar.DATE,-1);
//            4、获取这天的日期并输出
            int day = ca.get(Calendar.DATE);
            System.out.println(i+"年2月份一共有"+day+"天");

Guess you like

Origin blog.csdn.net/weixin_52723971/article/details/110431588