Java日历的设置值不会提供预期的日期时间

前端之家收集整理的这篇文章主要介绍了Java日历的设置值不会提供预期的日期时间前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个小时,分钟,日期和毫秒时间戳,并且正在尝试创建一个表示时间的Date对象.时间戳在Eastern Daylight Time中提供.

在解剖这个问题时,我创建了一些简单的测试代码来看看发生了什么,并且已经观察到以下内容

Date today = new Date();
    int hour = 4,min  = 0,sec  = 0,ms   = 64;
    boolean print = true;

    Calendar cal = GregorianCalendar.getInstance();
    if(print)
        System.out.println("After initializing,time is: "+cal.getTime());
    cal.clear();
    if(print)
        System.out.println("After clearing,time is: "+cal.getTime());
    cal.setTime(today);
    if(print)
        System.out.println("After setting date,time is: "+cal.getTime());
    cal.set(Calendar.HOUR_OF_DAY,hour);
    if(print)
        System.out.println("After setting hour,time is: "+cal.getTime());
    cal.set(Calendar.MINUTE,min);
    if(print)
        System.out.println("After setting minute,time is: "+cal.getTime());
    cal.set(Calendar.SECOND,sec);
    if(print)
        System.out.println("After setting second,time is: "+cal.getTime());
    cal.set(Calendar.MILLISECOND,ms);
    if(print)
        System.out.println("After setting milliseconds,time is: "+cal.getTime());
    cal.setTimeZone(TimeZone.getTimeZone("EDT"));

    System.out.println("After setting time zone,time is: "+cal.getTime());

这产生的输出

After initializing,time is: Tue Jan 07 16:01:59 EST 2014
After clearing,time is: Thu Jan 01 00:00:00 EST 1970
After setting date,time is: Tue Jan 07 16:01:59 EST 2014
After setting hour,time is: Tue Jan 07 04:01:59 EST 2014
After setting minute,time is: Tue Jan 07 04:00:59 EST 2014
After setting second,time is: Tue Jan 07 04:00:00 EST 2014
After setting milliseconds,time is: Tue Jan 07 04:00:00 EST 2014
After setting time zone,time is: Tue Jan 07 04:00:00 EST 2014

但是,如果我稍微更改代码

boolean print = false;

我得到以下(不同)结果(!)

After setting time zone,time is: Mon Jan 06 23:00:00 EST 2014

有人知道为什么会发生这种情况吗?

解决方法

您需要先设置时区.请参阅下面的GregorianCalendar.setTimeZone的定义:
public void setTimeZone(TimeZone value)
{
    zone = value;
    sharedZone = false;
    /* Recompute the fields from the time using the new zone.  This also
     * works if isTimeSet is false (after a call to set()).  In that case
     * the time will be computed from the fields using the new zone,then
     * the fields will get recomputed from that.  Consider the sequence of
     * calls: cal.setTimeZone(EST); cal.set(HOUR,1); cal.setTimeZone(PST).
     * Is cal set to 1 o'clock EST or 1 o'clock PST?  Answer: PST.  More
     * generally,a call to setTimeZone() affects calls to set() BEFORE AND
     * AFTER it up to the next call to complete().
     */
    areAllFieldsSet = areFieldsSet = false;
}
原文链接:https://www.f2er.com/java/123667.html

猜你在找的Java相关文章