Detailed explanation of Java.util.Date of commonly used libraries

Detailed explanation of date classes commonly used in Java

Overview of the Date class-JDK11API

The Date class represents a specific moment, with an accuracy of milliseconds.

public class Date
extends Object
implements Serializable, Cloneable, Comparable<Date>

According to the statement when the Datel class is created, it can be seen that the Date class is serializable, cloneable, and comparable, and has a fixed comparison order.


Before JDK 1.1, the Date class had two additional functions. It allows the date to be interpreted as year, month, day, hour, minute, and second values. It also allows formatting and parsing date strings. Unfortunately, these functional APIs are not suitable for internationalization. Starting from JDK 1.1, the Calendar class should be used to convert between date and time fields, and the DateFormat class should be used to format and parse date strings. The corresponding method in Date is not recommended.


In all Date class methods that accept or return year, month, day, hour, minute, and second values, use the following notation:

  • A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so on; so November is December.
  • The hour is represented by an integer between 0 and 23. Therefore, the hour from midnight to 1:00 am is hour 0, and the hour from noon to 1:00 pm is hour 12.
  • One minute is represented by an integer from 0 to 59 in the usual way.

Create Date object

Date()

The Date object created by this method is the current time

源码:
public Date() {
     
     
	this(System.currentTimeMillis());
//注释:System.currentTimeMillis() 可以获得当前时间的毫秒数
}
Date()方法的使用:
Date()   分配 Date对象并对其进行初始化,使其表示分配时间,测量 Date到毫秒。 
Date date = new Date();
System.out.println(date);
打印结果:Sun Jan 24 00:47:54 CST 2021

The default format of the Date object is "day of the week, month, day, hour: minute: second, regional year".
CST means China Standard Time, which is Beijing time, Dongba District.

Date(long time)

This method can create a Date object at a specified time, and set the specified time by a given number of milliseconds (Note: The number of milliseconds is the difference between the current time and 00:00:00 GMT on January 1, 1970, but because we are in The East Eight District is actually the difference from 00:08:00 on January 1, 1970)

源码:
public Date(long date) {
     
     
	fastTime = date;
}
方法的使用:
Date(long time) 分配 Date对象并初始化它以表示自标准基准时间(称为“纪元”)以来的指定毫秒数,即19701100:00:00 GMT。 
long time1 = 1611420846276L;
Date date1 = new Date(time1);
System.out.println(date1);
打印结果:Sun Jan 24 00:54:06 CST 2021
这里面要注意 time 赋值的 long类型的数字已经超过了int 的存储范围,要在数字后面加上L,不然会报错"Integer number too large".

但我们一般很少直接写个如此之大的毫秒数来设置时间。下面给定一种新的设置时间的格式。
long time2 = System.currentTimeMillis();
//注释:System.currentTimeMillis() 可以获得当前时间的毫秒数
System.out.println(time2);
Date date2 = new Date(time2);
System.out.println(date2);
打印结果:1611422082340    Sun Jan 24 01:14:42 CST 2021

Later we learn the Calendar class and DateFormat class, we have more ways to generate Date, such as inputting a string to specify the time to generate the Date object of the time, etc., but they are all called Date() and Date(long time ) These two methods.

Common methods of the Date class (non-obsolete methods)

方法after(Date when)

源码:
public boolean after(Date when) {
     
     
	return getMillisOf(this) > getMillisOf(when);
}

According to the source code, it is not difficult to see that the data type of the return value of this method is boolean.
The function of this method is to test whether the date of the Date object is after the specified date.
Result: true if and only if the time represented by this Date object is strictly later than when represented by when; otherwise, it is false.

after(Date when)方法的使用:
//使用之前创建过得date1和date2
boolean test1 = date1.after(date2);
System.out.println(test1);
打印结果: false  // 表示date1 早于 date2
可能发生的异常:NullPointerException - 如果 when为空。

方法before​(Date when)

源码:
public boolean before(Date when) {
     
     
	return getMillisOf(this) < getMillisOf(when);
}

The data type of the return value of this method is boolean.
Function: Test whether this date is before the specified date.
Result: true if and only if the time represented by this Date object is strictly earlier than when represented by when; false otherwise.

before(Date when)方法的使用:
//使用之前创建过得date1和date2
boolean test2 = date1.before(date2);
System.out.println(test2);
打印结果: true

可能出现的异常:NullPointerException - 如果 when为空。 

方法compareTo(Date anotherDate)

源码:
public int compareTo(Date anotherDate) {
     
     
	long thisTime = getMillisOf(this);
	long anotherTime = getMillisOf(anotherDate);
	return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
//如果thisTime小则返回-1,相等返回0,大于返回1.

The data type of the return value of this method is int.
Role: Compare the order of two Date objects.

compareTo(Date anotherDate)方法的使用:
//使用之前创建过得date1和date2
int order = date1.compareTo(date2);
System.out.println(order);
打印结果: -1    // 表示date1的顺序在date2之前 即date1早于date2

可能放生的异常:NullPointerException - 如果 anotherDate为空。

Method equals​(Object obj)

public boolean equals(Object obj) {
     
        // obj - 要与之比较的对象。 
	return obj instanceof Date && getTime() == ((Date) obj).getTime();
}

The data type of the return value of this method is boolean.
The function of this method: compare the contents of two Date objects, that is, whether the time milliseconds are equal.
Result: true if the objects are the same; otherwise, false.

equals(Object obj)方法的使用:
//使用之前创建过得date1和date2
boolean test3 = date1.equals(date2);
打印结果:false     // 表示两个Date对象的时间不相等

Method getTime()

源码:
public long getTime() {
     
     
	return getTimeImpl();  
}
//调用的这个方法是私有的不细究了,大概作用是判断时间是否是标准化时间,如果不是则变成标准化的时间再返回对应的毫秒数,涉及到Calendar类

The data type of the return value of this method is long.
The function is to return the number of milliseconds since January 1, 1970 00:00:00 GMT represented by this Date object.

getTime()方法的使用:
//使用前面创建的对象date1
long getTime = date1.getTime();
System.out.println(getTime);
打印结果: 1611420846276    //与前面创建date1时赋值的毫秒数一致

Method setTime​(long time)

源码:
public void setTime(long time) {
     
     
	fastTime = time;
	cdate = null;
}

The type of this method is void and does not return a value.
Function: Set this Date object to represent the time point in time milliseconds after 00:00:00 on January 1, 1970, Greenwich Mean Time.
Parameters: time-the number of milliseconds.

setTime(long time)方法的使用:
//使用前面创建的对象date1与date2,变量time1
System.out.println(date1.equals(date2)?"date1与date2时间相同":"date1与date2时间不相同");
date2.setTime(time1);
System.out.println(date1.equals(date2)?"date1与date2时间相同":"date1与date2时间不相同");
打印结果: date1与date2时间不相同   date1与date2时间相同  //说明date2调用setTime()方法后时间已经变为date1的时间了。

Introduction to uncommon methods in the Date class

Method clone()

public Object clone()
It is an overriding of the clone() method in the Object class. The
method returns a copy of this object.
Result: a clone of this instance.
The classes involved in the source code will not be released if they are temporarily unavailable.
The essence of the clone method is to copy the content of the current object and assign it to a new Date object, so the returned copy has the same time milliseconds as the ontology, but the address of the copy is not equal to the ontology.

验证 clone()方法:
//使用前面创建的对象date1
Date date3 = (Date) date1.clone();
System.out.println(date1 == date3);
System.out.println(date1.equals(date3));
打印结果: false  true  // false表示两者地址不同即克隆出来的对象拥有新的地址, true表示两者内容相同

方法from​(Instant instant)

public static Date from(Instant instant)
Role: Obtain an instance of Date from the Instant object. The precision used by Instant is nanoseconds, while the precision used by Date is milliseconds. The conversion will truncate any excess precision information, as if an integer in nanoseconds is divided by one million. Instant can store points on the future timeline, and it is much larger than Date. In this case, this method will throw an exception IllegalArgumentException-if the instant is too large to be expressed as the Date
parameter instant-the instant in nanoseconds of the time
Result: The method returns a Date object, and Date represents the same point on the timeline as the provided instant
Starting from java version 1.8,
this method is basically not used at this stage and will not be demonstrated.

Method hashCode()

public int hashCode()
Role: Return the hash code value of this object. The result is the exclusive OR of the two halves of the original long value returned by the getTime() method. In other words, the hash code is the value of the expression:
(int)(this.getTime()^(this.getTime() >>> 32))
is the
result of rewriting the hashCode method in the class Object : the value of this object The hash code value.
The source code compiler can be automatically generated, basically for the purpose of realizing the hash table, basically it will not be shown if it is not used.

Method toInstant()

public Instant toInstant()
Function: Convert this Date object to Instant.
Result: The moment that represents the same point on the timeline as this Date object.
Starting from java 1.8.
Because the classes involved in this method are basically not used, the source code and method use display are not written.

Method toString()

public String toString()
The source code involves many classes that have not been learned and used for the time being, so I will not show the
function: convert this Date object into the following form of String:
dow mon dd hh:mm:ss zzz yyyy
explanation:
-dow is the day of the week ( Sun, Mon, Tue, Wed, Thu, Fri, Sat).
-mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
-dd is the day of the month (01 to 31), with two digits after the decimal point.
-hh is the hour of the day (00 to 23), with two digits after the decimal point.
-mm is the minute within the hour (00 to 59), with two digits after the decimal point.
-ss is the second of the minute (00 to 61, two decimal digits.
-zzz is the time zone (may reflect daylight saving time). Standard time zone abbreviations include those recognized by the parse method. If time zone information is not available, zzz is empty
-In other words, it contains no characters at all. -yyyy is the year, four digits.

toString()方法的使用:
//使用前面已创建的对象date1
System.out.println(date1.toString());
打印结果: Sun Jan 24 00:54:06 CST 2021

The reason why this method is not commonly used is that the format is too complicated. Later, we can set a simpler format for converting dates into strings in the DateFormat class, such as "yyyy-MM-dd" string display format for year, month, and day.

Guess you like

Origin blog.csdn.net/qq_40694640/article/details/113065334