我试图在保持实际日期/时间的同时更改日历对象的时区,以便可以在更新的日历对象上调用 getTimeInMilliseconds()。
我看着这个另一个问题。在这里,接受的答案是单独设置新日历对象的每个字段。但是,我可以通过简单地更改原始日历对象副本的时区来使其工作。奇怪的是,这只有在我在重置时区之前对原始日历进行一些修改时才有效。以下示例说明了不一致。
public void TestCalendar()
{
Calendar nextYear = Calendar.getInstance();
nextYear.add(Calendar.YEAR, 1);
log.info("Next Year: {}", getUTCMilliseconds(nextYear));
Calendar now = Calendar.getInstance();
log.info("Now: {}", getUTCMilliseconds(now));
}
protected String getUTCMilliseconds(Calendar cal)
{
// Create a new calendar so we don't modify input
Calendar expectedDbTime = (Calendar) cal.clone();
// Change the TimeZone the contained date is interpreted in
expectedDbTime.setTimeZone(TimeZone.getTimeZone("UTC"));
// Return millisecond value of this date in the UTC timezone
return String.valueOf(expectedDbTime.getTimeInMillis());
}
我在 2015 年 1 月 24 日下午 2:33 运行了这个程序,得到了以下输出:
Next Year: 1422110038529 //(Corresponding UTC Date: Sat Jan 24 2015 2:33:58 PM)
Now: 1390599238531 //(Corresponding UTC Date: Fri Jan 24 2014 9:33:58 PM)
如您所见, nextYear 按预期打印,但下一行与预期不符(它应该对应于 1/24/2014 2:33:58PM UTC,相反,它对应于当前日期/时间,即 1/24 /2014 2:33:58 MTN)。有人能告诉我这里发生了什么吗?
编辑:刚刚更新了一些格式。