我發現GregorianCalendar.getTimeInMillis()的一個非常奇怪的行爲,它似乎改變了實例內容的值。在下面的代碼中,您可以看到兩個代碼塊僅在一個註釋行中有所不同,其中getTimeInMillis()被調用。爲什麼我取消註釋時結果不同?爲什麼GregorianCalendar.getTimeInMillis()更改實例的值?
隨着評論調用輸出是
2014-10-25T22:00:00Z -> 2014-10-26T22:00:00.000+01:00
2014-10-25T22:00:00Z -> 2014-10-27T00:00:00.000+01:00
但是當我取消對getTimeInMillis()線,兩個結果都是相同的:
2014-10-25T22:00:00Z -> 2014-10-27T00:00:00.000+01:00
2014-10-25T22:00:00Z -> 2014-10-27T00:00:00.000+01:00
代碼:
package com.test;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class Main {
public static void main(String[] args) {
try {
XMLGregorianCalendar date1 = DatatypeFactory.newInstance()
.newXMLGregorianCalendar("2014-10-25T22:00:00Z");
XMLGregorianCalendar date2 = DatatypeFactory.newInstance()
.newXMLGregorianCalendar("2014-10-25T22:00:00Z");
int days = 1;
GregorianCalendar gregorianCalendar1 = date1.toGregorianCalendar();
// gregorianCalendar1.getTimeInMillis(); //UNCOMMENT THIS LINE TO GET A DIFFERENT RESULT
gregorianCalendar1.setTimeZone(TimeZone.getDefault());
gregorianCalendar1.add(Calendar.DAY_OF_MONTH, days);
XMLGregorianCalendar newXMLGregorianCalendar1 = DatatypeFactory
.newInstance().newXMLGregorianCalendar(gregorianCalendar1);
System.out.printf("%s -> %s\n", date1, newXMLGregorianCalendar1);
GregorianCalendar gregorianCalendar2 = date2.toGregorianCalendar();
gregorianCalendar2.getTimeInMillis();
gregorianCalendar2.setTimeZone(TimeZone.getDefault());
gregorianCalendar2.add(Calendar.DAY_OF_MONTH, days);
XMLGregorianCalendar newXMLGregorianCalendar2 = DatatypeFactory
.newInstance().newXMLGregorianCalendar(gregorianCalendar2);
System.out.printf("%s -> %s\n", date2, newXMLGregorianCalendar2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
此錯誤報告中也描述了此行爲:http://bugs.java.com/bugdatabase/view_bug.do?bug_id=5026826 – Marco13 2014-10-30 09:43:22