Date() and Date(long Date) constructor:

Public Date(): Allocates a Date object and initializes this object to indicate the time (to the millisecond) at which it was allocated. Public Date(Long Date): Allocates and initializes a Date object to represent the specified number of milliseconds since the standard base time (called epoch, or 00:00:00 GMT, January 1, 1970). Date - Number of milliseconds since 00:00:00 GMT, January 1, 1970.Copy the code

1. Get the current system time (to the millisecond)

Date nowTime = new Date(); // The toString() method of the java.util.Date class has been overridden system.out.println (nowTime); //Tue Jul 13 20:33:44 CST 2021Copy the code

2. Date formatting

(Reason) : The overwritten toString() method of the java.util.date class is not intuitive, so it needs to be formatted

SimpleDateFormat Format dates yyyy Year (4-bit year) MM month (2-bit month) DD day HH MM minute SS second SSS ms (3-bit milliseconds, maximum 999). 1000 ms = 1 second) note: In the date format, y, M, d, H, s, s cannot be written at random.  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); String nowTimeStr = sdf.format(nowTime); System.out.println(nowTimeStr);Copy the code

Given a Date String, how to convert it to Date:

String time = "2008-08-08 08:08:08 888"; /* The format of the SimpleDateFormat object must be the same as that of the string. java.text.ParseException */ SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); Date dateTime = sdf2.parse(time); System.out.println(dateTime); //Fri Aug 08 08:08:08 CST 2008Copy the code

System.currenttimemillis () method

Function: is a static method (underlying C++) that retrieves the total number of milliseconds since January 1, 1970 00:00:00 000 to the current system time. 1 second = 1000 ms // The total number of milliseconds from 00:00:00 000 on January 1, 1970 to the current system time. long nowTimeMillis = System.currentTimeMillis(); System.out.println(nowTimeMillis); / / 1626173654400Copy the code

Use the System.currentTimemillis () method to count the time spent on a method

Public class DateTest02 {public static void main(String[] args) {// Count the number of milliseconds before calling the target method long BEGIN = System.currentTimeMillis(); print(); Long end = System.currentTimemillis (); System.out.println(" end - begin + "); } public static void print(){for (int I = 0; i < 1000; i++){ System.out.println("i = " + i); }}}Copy the code

Obtain 1970-01-01 00:00:00 001

Date time = new Date(1); SimpleDateFormat SDF = new SimpleDateFormat(" YYY-MM-DD HH: MM :ss SSS"); String strTime = sdf.format(time); // Beijing is the East 8th District. System.out.println(strTime); / / 08:00:00 001 1970-01-01Copy the code

Get the time at this time yesterday

Date time2 = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24); String strTime2 = sdf.format(time2); System.out.println(strTime2); / / 19:54:43 821 2021-07-12Copy the code