Java basic study notes _Date class and Calendar class

table of Contents

Overview:

Date class:

Calendar class:


Overview:

Date class: The java.util package provides the Date class to encapsulate the current date and time. The Date class provides two constructors to instantiate Date objects.

Calendar class: The function of the Calendar class is much more powerful than that of the Date class, and its implementation is more complicated than that of the Date class.

                             The Calendar class is an abstract class that implements a specific subclass of objects in actual use. The process of creating an object is transparent to the programmer and only needs to be created using the getInstance method.

Date class:

Construction method:

Date date = new Date();//构造一个日期对象,采用当前系统时间,精确到毫秒
Date date = new Date(long);//构造一个日期对象,时间自"1970年1月1日 00:00:00 GMT"起,至指定参数的毫秒数

Member method:

long getTime()  //将日期对象转换成对应时间的毫秒值

Test code: 

import java.util.Date;

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

        //测Date类
        //测试空参,采用当前操作系统的默认时间
        //date1:Thu Feb 04 16:51:38 CST 2021
        Date date1 = new Date();
        System.out.println("date1: " + date1);

        //获取当前操作系统的毫秒值
        //1612428698133
        long time = date1.getTime();
        System.out.println(time);

        //创建一个指定时间:1612428698133
        Date date2 = new Date(1612428698133L);//注意long类型的值在最后面加L
        System.out.println("dare2: " + date2);
    }
}

Output result:

date1: Thu Feb 04 18:16:01 CST 2021
1612433761495
dare2: Thu Feb 04 16:51:38 CST 2021

Calendar class:

Create Calendar object:

Calendar c = Calendar.getInstance();//静态方法,直接 类名. 调用

Member method:

int get(int filed)  //返回给定日历字段的值
void set(int filed, int value)  //将给定的日历字段设置为指定的值

Test code:

import java.util.Calendar;

public class Test2 {
    public static void main(String[] args) {
        //测试Calendar类
        //创建Calendar类型的对象
        //Calendar是抽象类,不可以直接new
        Calendar c = Calendar.getInstance();
        //System.out.println(c);
        int year = c.get(Calendar.YEAR);//静态方法,创建Calendar类型的对象
        int month = c.get(Calendar.MONTH);//Java中使用0-11表示月份,对应1-12月
        int day = c.get(Calendar.DATE);
        System.out.println(year + "年" + (month + 1) + "月" + day + "日");

        //设定时间为2022年2月2日
        c.set(Calendar.YEAR, 2022);
        int year2 = c.get(Calendar.YEAR);
        System.out.println(year2 + "年" + (month + 1) + "月" + day + "日");
        c.set(2022, 8, 9);
        int month2 = c.get(Calendar.MONTH);
        int day2 = c.get(Calendar.DATE);
        System.out.println(year2 + "年" + (month2 + 1) + "月" + day2 + "日");



    }
}

Output result:

2021年2月4日
2022年2月4日
2022年9月9日

 

Guess you like

Origin blog.csdn.net/qq_43191910/article/details/113660170