JAVA中的日期比较问题
PHP中文网
PHP中文网 2017-04-17 15:57:25
[Java讨论组]

JAVA中的日期用Date.before()和Date.after(),还是直接Date.getTime比较,哪个好?

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(1)
PHP中文网

根据 OpenJDK 7 的源代码:

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

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

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

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

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

private final BaseCalendar.Date normalize() {
    if (cdate == null) {
        BaseCalendar cal = getCalendarSystem(fastTime);
        cdate = (BaseCalendar.Date) cal.getCalendarDate(fastTime, TimeZone.getDefaultRef());
        return cdate;
    }
    if (!cdate.isNormalized()) {
        cdate = normalize(cdate);
    }
    TimeZone tz = TimeZone.getDefaultRef();
    if (tz != cdate.getZone()) {
        cdate.setZone(tz);
        CalendarSystem cal = getCalendarSystem(cdate);
        cal.getCalendarDate(fastTime, cdate);
    }
    return cdate;
}

看起来 before 和 after 会稍微快一点点。不过也有的 Java 实现里面 beforeafter 就是调用 getTime() 的。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号