java.util.Date class

Let's start with a small piece of code to see what the output is?

public static void main(String[] args) {
    
    
    java.util.Date udate = new java.util.Date();
    System.out.println(udate);
}

Output: Sat Dec 26 13:19:54 CST 2020
Explanation:
Sat Saturday
Dec
26th
CST The local standard time of China, the United States, Australia, and Cuba

Output the local format time (toLocaleString), but this method is outdated, the official recommendation is to use DateFormat for conversion, but there are some people who use toLocaleString

public static void main(String[] args) {
    
    
    Date udate1 = new Date();
    System.out.println(udate1.toLocaleString());
}

Output: 2020-12-26 14:20:38

Use milliseconds to get Date (used when converting time in different formats)

public static void main(String[] args) {
    
    
    Date udate1 = new Date();
    //休眠三秒,更容易对比
    try {
    
    
        Thread.sleep(3000);
    } catch (InterruptedException e) {
    
    
        e.printStackTrace();
    }

    Date udate2 = new Date(udate1.getTime());
    System.out.println("时间1:"+udate1.toLocaleString());
    System.out.println("时间2:"+udate2.toLocaleString());
}

Output:
Time 1: 2020-12-26 14:23:20
Time 2: 2020-12-26 14:23:20

Time comparison (compareTo), java.util.Date implements the Comparable interface, so there is a comparison function

public static void main(String[] args) {
    
    
    Date udate1 = new Date();
    //休眠三秒,使udate2时间更大三秒
    try {
    
    
        Thread.sleep(3000);
    } catch (InterruptedException e) {
    
    
        e.printStackTrace();
    }
    Date udate2 = new Date();
    System.out.println("时间1:"+udate1.toLocaleString());
    System.out.println("时间2:"+udate2.toLocaleString());
    System.out.println(udate1.compareTo(udate2));
}

Output:
Time 1: 2020-12-26 14:26:47
Time 2: 2020-12-26 14:26:50
-1
Explanation: Time 1. compareTo (Time 2)
Time 1> Time 2: Return a positive
time 1=Time 2: Return 0
Time 1<Time 2: Return a negative number

Guess you like

Origin blog.csdn.net/weixin_44613100/article/details/111825171