java Foundation series 20 (Date class)

1, Overview

Date class is an old class that has existed since JDK1.1. It provides many methods for date operation, but it has been criticized for its different starting numbers and low support for internationalization. JDK officials also recognize this problem. The background proposes to use Calendar class for date operation, and the date format is handed over to DateFormat, Although we no longer use most of the methods in the date class, we still have some reserved content values to talk about.

2, Constructor

Before the Date class, there are six constructors, four of which have been marked and discarded. We will not look at them, but focus on the other two:

public class Date
    implements java.io.Serializable, Cloneable, Comparable<Date>
{
    /**
     * Allocates a <code>Date</code> object and initializes it so that
     * it represents the time at which it was allocated, measured to the
     * nearest millisecond.
     *
     * @see     java.lang.System#currentTimeMillis()
     */
    public Date() {
        this(System.currentTimeMillis());
    }

    /**
     * Allocates a <code>Date</code> object and initializes it to
     * represent the specified number of milliseconds since the
     * standard base time known as "the epoch", namely January 1,
     * 1970, 00:00:00 GMT.
     *
     * @param   date   the milliseconds since January 1, 1970, 00:00:00 GMT.
     * @see     java.lang.System#currentTimeMillis()
     */
    public Date(long date) {
        fastTime = date;
    }
    //...
}

The first constructor is a parameterless constructor, which obtains the current timestamp by calling the currentTimeMillis() method of System. This timestamp is the millisecond data from 1970 to the current time. The second constructor can define a millisecond data as a Date in Date format.

3, Common methods

Many Date operation methods are defined in date, but most of them have been discarded, and only a few methods remain:

public class Date
    implements java.io.Serializable, Cloneable, Comparable<Date>
{
    /**
     * Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
     * represented by this <tt>Date</tt> object.
     *
     * @return  the number of milliseconds since January 1, 1970, 00:00:00 GMT
     *          represented by this date.
     */
    public long getTime() {
        return getTimeImpl();
    }

    /**
     * Sets this <code>Date</code> object to represent a point in time that is
     * <code>time</code> milliseconds after January 1, 1970 00:00:00 GMT.
     *
     * @param   time   the number of milliseconds.
     */    
    public void setTime(long time) {
        fastTime = time;
        cdate = null;
    }
    /**
     * Tests if this date is before the specified date.
     *
     * @param   when   a date.
     * @return  <code>true</code> if and only if the instant of time
     *            represented by this <tt>Date</tt> object is strictly
     *            earlier than the instant represented by <tt>when</tt>;
     *          <code>false</code> otherwise.
     * @exception NullPointerException if <code>when</code> is null.
     */
    public boolean before(Date when) {
        return getMillisOf(this) < getMillisOf(when);
    }
    /**
     * Tests if this date is after the specified date.
     *
     * @param   when   a date.
     * @return  <code>true</code> if and only if the instant represented
     *          by this <tt>Date</tt> object is strictly later than the
     *          instant represented by <tt>when</tt>;
     *          <code>false</code> otherwise.
     * @exception NullPointerException if <code>when</code> is null.
     */
    public boolean after(Date when) {
        return getMillisOf(this) > getMillisOf(when);
    }
    //...
}

The four methods shown above are several common methods still used in the Date class:

  • long getTime() method: returns millisecond data from 00:00:00 in 1970 to the time represented by the Date object
  • void setTime(long time) method: set a Date object to represent the time point after a period of millisecond data from 00:00:00 in 1970
  • boolean before(Date when) method: judge whether the time point represented by the Date object is before the time point represented by when
  • boolean after(Date when) method: judge whether the time point represented by the Date object is after the time point represented by when

4, Other

The Date class implements the java.io.Serializable interface and can perform serialization and deserialization operations. The writeObject(ObjectOutputStream s) method and readObject(ObjectInputStream s) method are defined in the Date class to save and obtain the timestamp (long data) represented by the object when the Date object is serialized and deserialized, Because the fastTime field is decorated with transient, its contents will be filtered out by the serialization mechanism, and the timestamp (long type) of the time represented by the Date object is saved in this field

For details, see Java Foundation Series - serialization and deserialization

public class Date
    implements java.io.Serializable, Cloneable, Comparable<Date>
{
    private transient long fastTime;

    /**
     * Save the state of this object to a stream (i.e., serialize it).
     *
     * @serialData The value returned by <code>getTime()</code>
     *             is emitted (long).  This represents the offset from
     *             January 1, 1970, 00:00:00 GMT in milliseconds.
     */
    private void writeObject(ObjectOutputStream s)
         throws IOException
    {
        s.writeLong(getTimeImpl());
    }

    /**
     * Reconstitute this object from a stream (i.e., deserialize it).
     */
    private void readObject(ObjectInputStream s)
         throws IOException, ClassNotFoundException
    {
        fastTime = s.readLong();
    }
    //...
}

5, Instance resolution:

public class DateTest{
    public static void main(String[] args) {
        Date now = new Date();//Get current time
        Date when = new Date(10201020097865L);//Specify a point in time based on the timestamp definition
        boolean b1 = now.after(when);
        boolean b2 = now.before(when);
        Long d1 = now.getTime();
        Long d2 = when.getTime();
        
        System.out.println("now The value is:"+now);
        System.out.println("when The value is:"+when);
        System.out.println("b1 The value is:"+b1);
        System.out.println("b2 The value is:"+b2);
        System.out.println("d1 The value is:"+d1);
        System.out.println("d2 The value is:"+d2);
        
    }
}

The execution results are:

now The value is: Thu Jul 06 13:39:12 CST 2017
when The value is: Tue Apr 04 16:41:37 CST 2293
b1 The value is: false
b2 The value is: true
d1 Value: 1499319552116
d2 Value: 10201020097865

6, Summary

The Date class is not recommended now. Java recommends Calendar and DateFormat, or even SimpleDateFormat to replace it. The only remaining methods in Date are still very practical, especially the before and after methods, which can easily judge the sequence of two time points. Of course, the judgment condition is to convert your time into Date format and use the remaining two constructors of Date, Of course, you can also use the recommended SimpleDateFormat method to simply format the Date format string to get the time point in Date format, which will be learned later!

Keywords: Java Spring

Added by behrk2 on Wed, 17 Nov 2021 08:50:49 +0200