JAVA—Date and Calender

Date class:

Get the current time:

public class Test2 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        Date date = new Date();
        System.out.println(date.toString());
        //返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
        System.out.println(date.getTime());
    }
}
Mon Feb 01 11:58:56 CST 2021
1612151936712

Parse string lattice into date

public class Test2 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        SimpleDateFormat sdf =new SimpleDateFormat("HH:mm:ss");
        String input=args.length==0?"11:55:20":args[0];
        Date time=sdf.parse(input);
        System.out.println(time.toString());

    }
}

Insert picture description here

Thu Jan 01 19:19:19 CST 1970

Time formatting

public class Test2 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time =sdf.format(date);
        System.out.println(time);
    }
}
2021-02-01 15:49:01

Calender class:

Calendar is an abstract class and cannot be directly instantiated to obtain objects. Therefore, Calendar provides a method getInstance to obtain a Calendar object, and the obtained Calendar is initialized by the current time.

public class Test2 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        Date date=new Date();
        Calendar calendar=Calendar.getInstance();
        //calendar.setTime(date);

        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH);
        System.out.println(year);
        System.out.println(month+1);
    }
}

2021
2

Guess you like

Origin blog.csdn.net/qq_44371305/article/details/113505490