Joda的DateTime与java.util.Calendar不一致

时间:2015-11-30 10:16:23

标签: java datetime jodatime

我使用以下代码检查joda的DateTime和java.util.Calendar之间的一致性。这个结果是正确的,但如果我将2000年改为1900年,那么我将得到2个不同的结果。这是一个错误或其他原因造成的吗?

MODULE  for the   Modulate t=  50.00000
MODULE  for the    Modulate t=  54.00000
MODULE   overshoot  Modulate t=  58.00000
MODULE   fail for  Modulate t=  62.00000
MODULE   successful for the Modulate t=  66.00000

这是输出

Calendar c = Calendar.getInstance();
c.set(1900,0,1,0,0,0);  // Calendar's month is 0 based
c.set(Calendar.MILLISECOND, 0);
System.out.println(c.getTimeInMillis() / 1000);
DateTime dt = new DateTime(1900,1,1,0,0,0);   // joda's month is 1 based
System.out.println(dt.getMillis() / 1000);

1 个答案:

答案 0 :(得分:3)

它是别的东西:)

import org.joda.time.DateTime; 
import java.util.Calendar;

public class DateTester {

    public static void main(String[] args) {
        Calendar c = Calendar.getInstance();
        c.set(1900,0,1,0,0,0);
        c.set(Calendar.MILLISECOND, 0);
        System.out.println(c.getTimeInMillis()/1000);
        DateTime dt = new DateTime(1900,1,1,0,0,0);
        System.out.println(dt.getMillis()/1000);
    }
}

结果:

-2208992400
-2208992400

Process finished with exit code 0

它与UTC和您的时区之间的偏移有关。对于我的时区,它是1893

import org.joda.time.DateTime;  
import java.util.Calendar;

public class DateTester {
    public static void main(String[] args) {
        Calendar c = Calendar.getInstance();
        int i = 1900;
        boolean found = false;
        while (!found) {
            c.set(i,0,1,0,0,0);
            c.set(Calendar.MILLISECOND, 0);
            DateTime dt = new DateTime(i,1,1,0,0,0);
            found = !(c.getTimeInMillis() == dt.getMillis());
            if (found) {
                System.out.println("year: " + i);
                System.out.println(c.getTimeInMillis());
                System.out.println(dt.getMillis());
            }
            i--;
        }
    }
}

结果:

year: 1893
-2429830800000
-2429830408000

可以在时区数据库中检查UTC与设定时区之间的偏差