我正在尝试将毫秒时间戳转换为 XMLGregorianCalendar 并返回,但我似乎得到了错误的结果。难道我做错了什么?看来我的日子越来越好。
// Time stamp 01-Jan-0001 00:00:00.000
Long ts = -62135740800000L;
System.out.println(ts);
System.out.println(new Date(ts)); // Sat Jan 01 00:00:00 PST 1 .. Cool!
// to Gregorian Calendar
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(ts);
// to XML Gregorian Calendar
XMLGregorianCalendar xc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
// back to GC
GregorianCalendar gc2 = xc.toGregorianCalendar();
// to Timestamp
Long newTs = gc2.getTimeInMillis();
System.out.println(newTs); // -62135568000000 .. uh?
System.out.println(new Date(newTs)); // Mon Jan 03 00:00:00 PST 1 .. where did the extra days come from?
最佳答案
有趣 - 它适用于低至(大约)-10000000000000L(和正值)的值,但更大的负值会变得不一致。
如果打印出gc
、xc
和gc2
,就可以看出问题出在哪里(从XMLGregorianCalendar到GregorianCalendar
gc: java.util.GregorianCalendar[time=-62135740800000 ... DAY_OF_WEEK=7
xc: 0001-01-01T08:00:00.000Z
gc2: java.util.GregorianCalendar[time=? ... DAY_OF_WEEK=5
如果打印出 xc
的字段,您将得到 1,1,1。
System.out.println(xc.getYear());
System.out.println(xc.getMonth());
System.out.println(xc.getDay());
对于 gc2
,您得到 1,0,1(与 xc
匹配,因为月份在 GregorianCalendar 中从零开始)
System.out.println(gc2.get(gc2.YEAR));
System.out.println(gc2.get(gc2.MONTH));
System.out.println(gc2.get(gc2.DAY_OF_MONTH));
但是,添加这 3 个 println
调用会改变打印出 gc2
的输出! - gc2
的 time=?
输出更改为 time=-62135568000000
- 因此通过查询 GregorianCalendar< 触发了一些计算
对象; areFieldsSet
属性也从 false
更改为 true
。
两个 GregorianCalendar 的时区不同,但这并不能解释错误,即使您设置了明确的 TimeZone 和 Locale,该错误仍然存在。
关于java - Long 到 XMLGregorianCalendar 并返回到 Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12867130/