java.util.date源码分析

java.util.date源码分析

API简析:

类 Date 表示特定的瞬间,精确到毫秒。

在 JDK 1.1 之前,类 Date 有两个其他的函数。它允许把日期解释为年、月、日、小时、分钟和秒值。它也允许格式化和分析日期字符串。不过,这些函数的 API 不易于实现国际化。从 JDK 1.1 开始,应该使用 Calendar 类实现日期和时间字段之间转换,使用 DateFormat 类来格式化和分析日期字符串。Date 中的相应方法已废弃。

尽管 Date 类打算反映协调世界时 (UTC),但无法做到如此准确,这取决于 Java 虚拟机的主机环境。当前几乎所有操作系统都假定 1 天 = 24 × 60 × 60 = 86400 秒。但对于 UTC,大约每一两年出现一次额外的一秒,称为“闰秒”。闰秒始终作为当天的最后一秒增加,并且始终在 12 月 31 日或 6 月 30 日增加。例如,1995 年的最后一分钟是 61 秒,因为增加了闰秒。大多数计算机时钟不是特别的准确,因此不能反映闰秒的差别。

一些计算机标准是按照格林威治标准时 (GMT) 定义的,格林威治标准时和世界时 (UT) 是相等的。GMT 是标准的“民间”名称;UT 是相同标准的“科学”名称。UTC 和 UT 的区别是:UTC 是基于原子时钟的,UT 是基于天体观察的,两者在实际应用中难分轩轾。因为地球的旋转不是均匀的(它以复杂的方式减速和加速),所以 UT 始终不是均匀地流过。闰秒是根据需要引入 UTC 的,以便把 UTC 保持在 UT1 的 0.9 秒之内,UT1 是应用了某些更正的 UT 版本。

类声明:

public class Date
    implements java.io.Serializable, Cloneable, Comparable<Date>

变量:

1.gcal/jcal/cdate/defaultCenturyStart:看不懂这四个变量的作用,BaseCalendar这个类在API和源码中都没有找到

 private static final BaseCalendar gcal =
                CalendarSystem.getGregorianCalendar();
 private static BaseCalendar jcal;

 private transient BaseCalendar.Date cdate;

 private static int defaultCenturyStart;

2.fastTime:当前时间的毫秒表示(从1970.1.1开始算)

private transient long fastTime;

说明:transient(短暂的;转瞬即逝的;临时的)修饰符:表示当该对象被序列化时,该变量不参与序列化过程。

构造器:

1.Date():用当前时间的毫秒数来初始化fastTime;

public Date() {
        this(System.currentTimeMillis());
    }

2.Date(long date):用long类型来初始化fastTime

public Date(long date) {
        fastTime = date;
    }

3.废弃的构造器(还能用,但不推荐):用某个年月日时分秒来初始化

    @Deprecated
    public Date(int year, int month, int date) {
     this(year, month, date, 0, 0, 0);
    }

    @Deprecated
    public Date(int year, int month, int date, int hrs, int min) {
        this(year, month, date, hrs, min, 0);
    }

    @Deprecated
    public Date(int year, int month, int date, int hrs, int min, int sec) {
    int y = year + 1900;
    // month is 0-based. So we have to normalize month to support Long.MAX_VALUE.
    if (month >= 12) {
        y += month / 12;
        month %= 12;
    } else if (month < 0) {
        y += CalendarUtils.floorDivide(month, 12);
        month = CalendarUtils.mod(month, 12);
    }
    BaseCalendar cal = getCalendarSystem(y);
        cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());
    cdate.setNormalizedDate(y, month + 1, date).setTimeOfDay(hrs, min, sec, 0);
    getTimeImpl();
    cdate = null;
    }

    @Deprecated
    public Date(String s) {
        this(parse(s));
    }

类方法:

getMillisOf(Date date):得到参数Date对象的fastTime值

 static final long getMillisOf(Date date) {
    if (date.cdate == null) {
        return date.fastTime;
    }
    BaseCalendar.Date d = (BaseCalendar.Date) date.cdate.clone();
    return gcal.getTime(d);
    }

方法:

1.clone() :返回该Date对象的一个’副本’(虽然返回是Object,不过可以转成Date);

 public Object clone() {
        Date d = null;
        try {
            d = (Date)super.clone();
        if (cdate != null) {
        d.cdate = (BaseCalendar.Date) cdate.clone();
        }
        } catch (CloneNotSupportedException e) {} // Won't happen
        return d;
    }

2.getTime():得到fastTime。


 public long getTime() {
        return getTimeImpl();
    }

    private final long getTimeImpl() {
    if (cdate != null && !cdate.isNormalized()) {
        normalize();
    }
    return fastTime;
    }

3.setTime(long time):重新设置fastTime

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

4.before(Date when)/after(Date when):与when比较是早(before)还是晚(after)(相当于小于号和大于号)。

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

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

5.equals(Object obj):判断两个Date是否相等(通过比较fastTime值)

public boolean equals(Object obj) {
        return obj instanceof Date && getTime() == ((Date) obj).getTime();
    }

6.compareTo(Date anotherDate):定义比较两个Date对象的规则(通过fastTime值的大小)

public int compareTo(Date anotherDate) {
    long thisTime = getMillisOf(this);
    long anotherTime = getMillisOf(anotherDate);
    return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
    }

7.toString():将fastTime转换成”EEE MMM dd HH:mm:ss zzz yyyy”格式

public String toString() {
    // "EEE MMM dd HH:mm:ss zzz yyyy";
    BaseCalendar.Date date = normalize();
    StringBuilder sb = new StringBuilder(28);
    int index = date.getDayOfWeek();
    if (index == gcal.SUNDAY) {
        index = 8;
    }


    convertToAbbr(sb, wtb[index]).append(' ');            // EEE
    convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
    CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

    CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
    CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
    CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
    TimeZone zi = date.getZone();
    if (zi != null) {
        sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
    } else {
        sb.append("GMT");
    }
    sb.append(' ').append(date.getYear());  // yyyy
    return sb.toString();
    }


private static final StringBuilder convertToAbbr(StringBuilder sb, String name) {
    sb.append(Character.toUpperCase(name.charAt(0)));
    sb.append(name.charAt(1)).append(name.charAt(2));
    return sb;
    }
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值