Java基础系列-Date类


原创文章,转载请标注出处:《Java基础系列-Date类》


一、概述

Date类是从JDK1.1就开始存在的老类,其提供了针对日期进行操作的诸多方法,但其却一直饱受诟病,不同的起始编号,国际化的低支持,JDK官方也认识到这个问题,后台提出使用Calendar类进行日期操作,日期的格式化交给DateFormat,虽然我们已经不再使用Date类中的大多数方法,但是还有一部分保留的内容值的我们一谈。

二、构造器

Date类之前有6大构造器,其中四个已经标注弃用,我们不再看他,重点看另外两个:

public class Date
    implements java.io.Serializable, Cloneable, Comparable
{
    /**
     * Allocates a Date 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 Date 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;
    }
    //...
}

第一个构造器是无参构造器,通过调用System的currentTimeMillis()方法来获取当前时间戳,这个时间戳是从1970年到当前时间的毫秒级数据,第二个构造器,可以将一个毫秒级的数据定义为Date格式的日期。

三、常用方法

Date中定义了诸多的日期操作方法,但是大多数都已弃用,只剩余为数不多的几个方法:

public class Date
    implements java.io.Serializable, Cloneable, Comparable
{
    /**
     * Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
     * represented by this Date 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 Date object to represent a point in time that is
     * time 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  true if and only if the instant of time
     *            represented by this Date object is strictly
     *            earlier than the instant represented by when;
     *          false otherwise.
     * @exception NullPointerException if when 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  true if and only if the instant represented
     *          by this Date object is strictly later than the
     *          instant represented by when;
     *          false otherwise.
     * @exception NullPointerException if when is null.
     */
    public boolean after(Date when) {
        return getMillisOf(this) > getMillisOf(when);
    }
    //...
}

上面显示的四个方法是Date类中现在还在使用的几个常用方法:

  • long getTime()方法:返回从1970年00:00:00到Date对象所代表时间的毫秒级数据
  • void setTime(long time)方法:设置一个Date对象用来代表从1970年00:00:00开始的一段毫秒级数据后所代表的时间点
  • boolean before(Date when)方法:判断Date对象所代表的时间点是否在when所代表的时间点之前
  • boolean after(Date when)方法:判断Date对象所代表的时间点是否在when所代表的时间点之后

四、其他

Date类实现了java.io.Serializable接口,可以执行序列化与反序列化操作,在Date类中定义了writeObject(ObjectOutputStream s)方法和readObject(ObjectInputStream s)方法,分别用于在Date对象进行序列化和反序列化操作时将对象所代表的时间戳(long型数据)进行保存与获取,因为fastTime字段采用transient修饰,其内容会被序列化机制过滤掉,而这个字段内保存的是Date对象所代表时间的时间戳(long型)

有关内容详情见《Java基础系列-序列化与反序列化》

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

    /**
     * Save the state of this object to a stream (i.e., serialize it).
     *
     * @serialData The value returned by getTime()
     *             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();
    }
    //...
}

五、实例解析:

public class DateTest{
    public static void main(String[] args) {
        Date now = new Date();//获取当前时间
        Date when = new Date(10201020097865L);//根据时间戳定义指定时间点
        boolean b1 = now.after(when);
        boolean b2 = now.before(when);
        Long d1 = now.getTime();
        Long d2 = when.getTime();
        
        System.out.println("now值为:"+now);
        System.out.println("when值为:"+when);
        System.out.println("b1值为:"+b1);
        System.out.println("b2值为:"+b2);
        System.out.println("d1值为:"+d1);
        System.out.println("d2值为:"+d2);
        
    }
}

执行结果为:

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

六、总结

Date类现在并不推荐使用,Java推荐了Calendar和DateFormat,甚至SimpleDateFormat来替代它,Date中仅剩的几个方法仍然还很实用,尤其是before与after方法,可以很方便的判断两个时间点的先后,当然判断的条件是将你的时间转换成Date格式,使用Date剩余的两个构造器实现即可,当然也可以使用推荐的SimpleDateFormat方法进行简单的格式化日期格式字符串的方式得到Date格式的时间点,这些会在稍后了解到!

你可能感兴趣的:(Java基础系列-Date类)