The use of Date class, SimpleDateFormat class and calendar class in Java

1. Date class

1 Overview

Date class: represents a specific moment, accurate to milliseconds.

2.Construction method of Date class

2.1 public Date();

Official explanation: public Date(): allocates a Date object and initializes the object to indicate the time when it is allocated (accurate to milliseconds)

In layman's terms: public Date(): allocates a Date object and initializes the object, used to obtain the time of the current environment, accurate to milliseconds.

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

        Date date1 = new Date();
        System.out.println(date1);

    }
}

The output is as follows:

 2.2 public Date (long date);

Official explanation: public Date (long date): Allocate a Date object and initialize this object to represent the standard base time since.

In layman's terms: public Date (long date): allocate a Date object and initialize this object. The date variable is used to store the number of milliseconds and is used to calculate the time after date milliseconds since January 1, 1970 00:00:00 .

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

        Date date2 = new Date(215464654);
        System.out.println(date2);

    }
}

The output is as follows:

 3. Common methods of Date class

gettime(): used to get the number of milliseconds (timestamp) from January 1, 1970 00:00:00 GMT to the current time

public class Demo_01 {
    public static void main(String[] args) {
        Date date1 = new Date();
        long time = date1.getTime();
        System.out.println(time);
    }
}

The output is as follows:

2. SimpleDateFormat class

1 Overview

官方讲解:SimpleDateFormatIs a concrete class that formats and parses dates in a locale-dependent manner. It allows formatting (date -> text), parsing (text -> date) and normalization.

In layman’s terms:SimpleDateForma类就是用来实现字符串和日期之间的相互转换。

2.日期和时间模式

letter date or time element express Example
G Era identifier Text AD
y Year Year 1996; 96
M month of year Month July; Jul; 07
w week number in year Number 27
W week number in month Number 2
D days in year Number 189
d number of days in month Number 10
F week of month Number 2
E Days of the week Text Tuesday;Tue
a Am/pm mark Text PM
H Hour of day (0-23) Number 0
k Hour of day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m minutes in hour Number 30
s seconds in minutes Number 55
S milliseconds Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800

 3. Common methods in the SimpleDateFormat class

3.1 format(): Convert the date into a string in the specified format

public class Demo_02 {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = new Date();
        String format = sdf.format(date1);
        System.out.println(format);
    }
}

The output is as follows:

3.2 parse(): Convert a string in a specified format into a date

Supplement: The parse() method cannot be used directly and needs to handle exceptions before it can be used.

public class Demo_02 {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = "1998-09-21 8:20:38";
        try {
            Date date2 = sdf.parse(time);
            System.out.println(date2);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

The output is as follows:

3. Calendar class

1 Overview

Official explanation:Calendar A class is an abstract class, which is a specific moment. Calendar provides a class method getInstance to obtain a generic object of this type.

In layman's terms: the Calendar class is an abstract class that can return a Calendar object through Calendar's getInstance() method.

2. Summary of common fields

DATE Represents a day of the month
DAY_OF_MONTH Represents a day of the month
DAY_OF_WEEK Indicates a day of the week
DAY_OF_WEEK_IN_MONTH Represents the week number of the current month
DAY_OF_YEAR Represents the number of days in the current year
AM means morning (the time between midnight and noon)
AM_PM Specify AM or PM (indicates whether HOUR is before or after noon)
PM means afternoon (time between noon and midnight)
HOUR Indicates the time in the morning or afternoon (AM_PM needs to be used at the end to indicate the time in the morning or afternoon)
HOUR_OF_DAY Represents the hour of the day
MILLISECOND Represents milliseconds in one second
MINUTE Represents the minutes of the hour
MONTH Indicates the month
SECOND Display seconds
WEEK_OF_MONTH Represents the week number in the current month
WEEK_OF_YEAR Indicates the number of weeks in the current year
YEAR Indicates the year

3. Common methods of Calendar class

3.1 getTime();

getTime(): used to get the current system time

public class Demo_03 {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        Date date1 = calendar.getTime();
        System.out.println("当前时间为:"+date1);
    }
}

The output is as follows:

 3.2 get();

The get() method is used to obtain the value of the specified field.

public class Demo_03 {
    public static void main(String[] args) {
        //get方法可以根据 指定的日历字段 获取时间对应的值
        //calendar.get(Calendar.YEAR) 获取 年
        int year = calendar.get(Calendar.YEAR);
        System.out.println("年份:"+year);

        //calendar.get(Calendar.MONTH) 获取 月份
        int month = calendar.get(Calendar.MONTH);//从0开始 11结尾 所以月份得加1
        System.out.println("月份:"+(month+1));

        //calendar.get(Calendar.DAY_OF_MONTH); 获取在月份中的天数(日)
        int date = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println("一个月中的第:"+date+"天");

        //calendar.get(Calendar.DAY_OF_YEAR); 获取在本年中的第几天
        int day_of_Year = calendar.get(Calendar.DAY_OF_YEAR);
        System.out.println("一年中的第:"+day_of_Year+"天");
    }
}

 The output is as follows:

3.3 set();

The set() method is used to assign a value to a field.

public class Demo_03 {
    public static void main(String[] args) {
        //可以获取 指定时间 月份0-11 表示 1-12月
        // second:61 可以自动根据时间转换进一位
        calendar.set(2000,9,28,15,46,61);
        Date date2 = calendar.getTime();
        System.out.println(date2);
    }
}

The output is as follows:

3.4 getTimeInMills();

The getTimeInMillis() method returns the number of milliseconds that have elapsed since the epoch (00:00:00.000 GMT on January 1, 1970, Gregorian calendar).
public class Demo_03 {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        long timeInMillis = calendar.getTimeInMillis();
        System.out.println("当前时间的毫秒值:"+timeInMillis);
    }
}

The output is as follows:

3.5  getTimeZone();

The getTimeZone() method is used to obtain the time zone.

public class Demo_03 {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        TimeZone timeZone = calendar.getTimeZone();
        System.out.println("所在时区:"+timeZone);
    }
}

 The output is as follows:

4. Extended practice questions

Question: The user enters the date, month, day, hour, minute, and second of birth according to the format to calculate how old he is?

The implementation code is as follows:

package com.hp.Test09;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

/**
 * 拓展作业: 用户按照格式输入出生年月日 时分秒   计算他几岁了?
 */
public class Demo_04 {
    public static void main(String[] args) {
        //提示用户需要输入的出生日期格式
        System.out.println("请根据----年--月--日--时--分--秒 的格式来输入你的出生日期");
        //实现键盘录入
        Scanner scanner = new Scanner(System.in);
        String dateTime=scanner.next();
        //使用SimpleDateFormat类把用户输入的出生日期字符串转换为日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        try {
            //把键盘录入的出生日期字符串转换为日期对象
            Date born = sdf.parse(dateTime);
            //获取当前时间
            Date current_Time = new Date();
            //把录入日前转换为毫秒数
            long new_born = born.getTime();
            //把当前日期转换为毫秒数
            long new_Current_Time = current_Time.getTime();
            //求出年龄毫秒数
            long years = new_Current_Time - new_born;
            int new_years = (int) (years / 1000 / 60 / 60 / 24 / 365);
            System.out.println("你今年"+new_years+"岁了,已经是成年人了。");


        } catch (ParseException e) {
            throw new RuntimeException(e);
        }


    }
}

The output is as follows:

 

Guess you like

Origin blog.csdn.net/m0_71385552/article/details/128152834