[Java] date time class

catalogue

1, Date class

1. Overview

2. Common methods

2, DateFormat class

1. Overview

2. Construction method

3. Format Rules

4. Common methods

(1) format method

(2) parse method

3, Practice

4, Calendar Class

1. Concept

2. Acquisition method

3. Common methods

1, Date class

1. Overview

    java.util.Date: class representing date and time
Class Date represents a specific moment, accurate to milliseconds.
Milliseconds: thousandth of a second 1000 milliseconds = 1 second
A specific moment: a point in time, a moment in time
2088-08-08 09:55:33:333 instant
2088-08-08 09:55:33:334 instant
2088-08-08 09:55:33:334 instant
    ...
Millisecond value: it can calculate time and date
How many days are there between October 7, 2020 and January 20, 2022
You can convert the date into milliseconds for calculation. After calculation, you can convert milliseconds into dates

Convert date to milliseconds:
Current date: 2088-01-01
Time origin (0 ms): January 1, 1970 00:00:00 (Greenwich, UK)
This is to calculate the total number of milliseconds (3742767540068L) between the current date and the time origin
Note:
China belongs to the East eighth District, which will increase the time by 8 hours
January 1, 1970 08:00:00

Convert milliseconds to date:
1 day = 24 × sixty × 60 = 86400 seconds = 86400 x 1000 = 86400000 milliseconds

2. Common methods

java. util. The date class represents a specific moment, accurate to milliseconds.

public Date() allocates a Date object and initializes it to represent the time (in milliseconds) at which it was allocated.

public Date(long date)     distribution Date Object and initialize this object to represent the time since the standard base time (called " calendar
Yuan (epoch) ”, i.e 1970 year 1 month 1 day The specified number of milliseconds since 00:00:00 GMT).

To put it simply: using the nonparametric structure, you can automatically set the millisecond time of the current system time; appoint long Type. You can customize the millisecond time. For example:
import java.util.Date; 

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

    // Create a date object and put the current time 
    System.out.println(new Date()); // Tue Jan 20 14:37:35 CST 2022

    // Create a date object and convert the current millisecond value into a date object 
    System.out.println(new Date(0L)); // Thu Jan 01 08:00:00 CST 1970 
    } 
}
tips: in use println Method is called automatically Date Class toString method. Date Class pair Object Class toString Method is overridden, so the result is a string in the specified format.
public long getTime() Convert the date object to the corresponding time millisecond value.
public String toLocaleString() converts date objects according to local format
long getTime() converts the Date to a millisecond value (equivalent to the System.currentTimeMillis() method) and returns the number of milliseconds represented by this Date object since 00:00:00 GMT, January 1, 1970.
import java.util.Date;

public class Demo02Date {
    public static void main(String[] args) {
        demo();
    }

    /*
        long getTime() Convert the date to a millisecond value (equivalent to the System.currentTimeMillis() method)
          Returns the number of milliseconds represented by this Date object since January 1, 1970, 00:00:00 GMT.
     */
    private static void demo() {
        Date date = new Date();
        long time = date.getTime();
        System.out.println(time); //1642667329975
    }
}
import java.util.Date;

public class test {
    public static void main(String[] args) {
        Date d = new Date();
        System.out.println(d.toLocaleString());  // January 20, 2022 8:01:46 PM
    }
}

2, DateFormat class

1. Overview

java.text.DateFormat It's the date / The abstract class of time formatting subclass, which can help us complete the conversion between date and text, That is, you can Date Object and String Objects.
format From the specified format: Date Object to String Object.
analysis From the specified format: String Object to Date Object.

java.text.DateFormat: is an abstract class of date / time formatting subclass
Function:
Formatting (i.e. date - > text), parsing (text - > date)
Member method:
String format(Date date) formats the Date into a string matching the pattern according to the specified pattern
Date parse(String source) parses the string conforming to the pattern into a date date
DateFormat class is an abstract class and cannot be used to create objects directly. You can use the subclass of DateFormat class

    java.text.SimpleDateFormat extends DateFormat

Construction method:
        SimpleDateFormat(String pattern)
Construct a SimpleDateFormat with the date format symbols of the given schema and the default locale.
Parameters:
String pattern: pass the specified pattern
Mode: case sensitive
y # year
M # month
d) day
H +
m , min
S} s
Writing the corresponding pattern will replace the pattern with the corresponding date and time
            "yyyy-MM-dd HH:mm:ss"
Note:
The letters in the mode cannot be changed, and the symbols of the connection mode can be changed
"yyyy MM dd HH h mm min ss s"

2. Construction method

because DateFormat It is an abstract class and cannot be used directly, so it needs common subclasses java.text.SimpleDateFormat . This class requires a schema (format) to specify the standard for formatting or parsing. The construction method is:
public SimpleDateFormat(String pattern) constructs a SimpleDateFormat with the date format symbols of the given schema and the default locale. parameter pattern Is a string representing the custom format of date and time.

3. Format Rules

Identification letters (case sensitive)meaning
yyear
Mmonth
dday
HTime
mbranch
ssecond
establish SimpleDateFormat Object code, such as:
import java.text.DateFormat; 
import java.text.SimpleDateFormat; 

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

        // The corresponding date format is as follows: 2022 ‐ 01 ‐ 20 15:06:38 
        DateFormat format = new SimpleDateFormat("yyyy‐MM‐dd HH:mm:ss"); 
    } 
}

4. Common methods

public String format(Date date) Will: Date Object is formatted as a string.
public Date parse(String source): parses a string into Date Object.

(1) format method

use format The code of the method is:
import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

/*Convert Date object to String */

public class Demo03DateFormatMethod {
    public static void main(String[] args) { 
        Date date = new Date(); 
        // Create a date format object. You can specify the style when obtaining the format object 
        DateFormat df = new SimpleDateFormat("yyyy year MM month dd day"); 
        String str = df.format(date); 
        System.out.println(str); // January 20, 2020 
    } 
}

(2) parse method

Use the parse method in the DateFormat class to parse the text into a date

Use steps:

1. Create a SimpleDateFormat object and pass the specified pattern in the constructor

2. Call the parse method in the SimpleDateFormat object to parse the string that conforms to the pattern in the construction method into a Date date

Note:
                public Date parse(String source) throws ParseException
The parse method declares an exception called ParseException parsing exception
If the pattern of string and constructor is different, the program will throw this exception
When calling a method that throws an exception, you must handle the exception. Either throw continues to throw the exception, or try catch handles the exception itself

use parse The code of the method is:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*Convert String to Date object */

public class Demo04DateFormatMethod {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy year MM month dd day");
        String str = "2022 January 20";
        Date date = df.parse(str);
        System.out.println(date); // Thu Jan 20 00:00:00 CST 2022
    }
}

3, Practice

practice:
Please use the date and time related API to calculate how many days a person has been born.

analysis:
        1. Use the method next in the Scanner class to get the date of birth
        2. Use the parse method in the DateFormat class to parse the birth Date of the string into the birth Date in Date format
        3. Converts the Date of birth in Date format to a millisecond value
        4. Gets the current date and converts it to a millisecond value
        5. Use the millisecond value of the current date - the millisecond value of the birth date
        6. Convert millisecond difference to days (s/1000/60/60/24)
Code implementation:
public static void function() throws Exception { 
    System.out.println("Please enter birth date format YYYY‐MM‐dd"); 
    // Get the date of birth and enter it with the keyboard 
    String birthdayString = new Scanner(System.in).next(); 

    // Convert a Date string to a Date object 
    // Create a SimpleDateFormat object to write the date pattern 
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy‐MM‐dd"); 
    // Call the parse method to convert the string into a date object 
    Date birthdayDate = sdf.parse(birthdayString); 

    // Get today's Date object 
    Date todayDate = new Date(); 
    
    // Convert the two dates into millisecond values, and the method getTime of the Date class 
    long birthdaySecond = birthdayDate.getTime(); 
    long todaySecond = todayDate.getTime(); 
    long secone = todaySecond‐birthdaySecond; 
    
    if (secone < 0){ 
        System.out.println("Not yet born"); 
    } 
    else { 
        System.out.println(secone/1000/60/60/24); 
    } 
}

4, Calendar Class

1. Concept

java.util.Calendar Is a calendar class, in Date After that, many were replaced Date Methods. This class encapsulates all possible time information into static member variables for easy access. Calendar class is convenient to obtain various time attributes.

2. Acquisition method

Calendar It is an abstract class. Due to language sensitivity, Calendar Class is not created directly when creating an object, but is created through a static method. The subclass object is returned as follows:
Calendar Static method
public static Calendar getInstance() gets a calendar using the default time zone and locale
For example:
import java.util.Calendar; 

public class Demo06CalendarInit { 
    public static void main(String[] args) { 
        Calendar cal = Calendar.getInstance(); 
    }
}

3. Common methods

public int get(int field)    Returns the value of the given calendar field.
public void set(int field, int value)    Sets the given calendar field to the given value.
public abstract void add(int field, int amount)    Adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar.
public Date getTime()    Returns a value representing this Calendar Time value (millisecond offset from epoch to present) Date Object.
Calendar Class provides many member constants that represent a given calendar field:
field valuemeaning
YEAR
year
MONTHMonth (starting from 0, can be used with + 1)
DAY_OF_MONTHDay (day) of the month
HOURHour (12 hour system)
HOUR_OF_DAYHour (24-hour system)
MINUTEbranch
SECONDsecond
DAY_OF_WEEKDay of the week (day of the week, Sunday is 1, can be - 1)
import java.util.Calendar;
import java.util.Date;

/*
    Calendar Common member methods of class:
        public int get(int field): Returns the value of the given calendar field.
        public void set(int field, int value): Sets the given calendar field to the given value.
        public abstract void add(int field, int amount): Adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar.
        public Date getTime(): Returns a Date object representing this Calendar time value (the millisecond offset from the epoch to the present).
    Parameters of member method:
        int field:The fields of Calendar class can be obtained by using the static member variable of Calendar class
            public static final int YEAR = 1;	year
            public static final int MONTH = 2;	month
            public static final int DATE = 5;	One day in the middle of the month
            public static final int DAY_OF_MONTH = 5;One day in the middle of the month
            public static final int HOUR = 10; 		Time
            public static final int MINUTE = 12; 	branch
            public static final int SECOND = 13;	second
 */
public class Demo02Calendar {
    public static void main(String[] args) {
        demo01();
        System.out.println("==============");
        demo02();
        System.out.println("==============");
        demo03();
        System.out.println("==============");
        demo04();
    }

    /*
        public Date getTime(): Returns a Date object representing this Calendar time value (the millisecond offset from the epoch to the present).
        Convert calendar object to date object
     */
    private static void demo04() {
        //Use the getInstance method to get the Calendar object
        Calendar c = Calendar.getInstance();

        Date date = c.getTime();
        System.out.println(date);  // Thu Jan 20 19:41:43 CST 2022
    }

    /*
        public abstract void add(int field, int amount): Adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar.
        Increases / decreases the specified field by the specified value
        Parameters:
            int field:Pass the specified calendar field (YEAR,MONTH...)
            int amount:Increases / decreases the specified value
                Positive: increase
                Negative: decrease
     */
    private static void demo03() {
        //Use the getInstance method to get the Calendar object
        Calendar c = Calendar.getInstance();

        //Increase the year by two years
        c.add(Calendar.YEAR,2);
        //Reduce the month by three months
        c.add(Calendar.MONTH,-3);


        int year = c.get(Calendar.YEAR);
        System.out.println(year);

        int month = c.get(Calendar.MONTH);
        System.out.println(month);//Month 0-11 in the West and 1-12 in the East

        //int date = c.get(Calendar.DAY_OF_MONTH);
        int date = c.get(Calendar.DATE);
        System.out.println(date);
    }

    /*
        public void set(int field, int value): Sets the given calendar field to the given value.
        Parameters:
            int field:Pass the specified calendar field (YEAR,MONTH...)
            int value:The value set for the specified field
     */
    private static void demo02() {
        //Use the getInstance method to get the Calendar object
        Calendar c = Calendar.getInstance();

        //Set year to 9999
        c.set(Calendar.YEAR,9999);
        //Set month to September
        c.set(Calendar.MONTH,9);
        //Set day 9
        c.set(Calendar.DATE,9);

        //At the same time, set the month, year and day. You can use the overload method of set
        c.set(8888,8,8);

        int year = c.get(Calendar.YEAR);
        System.out.println(year);

        int month = c.get(Calendar.MONTH);
        System.out.println(month);//Month 0-11 in the West and 1-12 in the East

        int date = c.get(Calendar.DATE);
        System.out.println(date);
    }

    /*
        public int get(int field): Returns the value of the given calendar field.
        Parameter: pass the specified calendar field (YEAR,MONTH...)
        Return value: the specific value represented by the calendar field
     */
    private static void demo01() {
        //Use the getInstance method to get the Calendar object
        Calendar c = Calendar.getInstance();
        int year = c.get(c.YEAR);
        System.out.println(year);

        int month = c.get(Calendar.MONTH);
        System.out.println(month);//Month 0-11 in the West and 1-12 in the East

        //int date = c.get(Calendar.DAY_OF_MONTH);
        int date = c.get(Calendar.DATE);
        System.out.println(date);
    }
}
The Western week starts on Sunday and China on Monday.
stay Calendar Class, the month is represented by 0-11 representative 1-12 Month.
The date has a size relationship. The later the time, the greater the time.

 

Keywords: Java

Added by Dia:NL on Fri, 21 Jan 2022 05:45:41 +0200