【发布时间】:2014-02-16 01:25:07
【问题描述】:
我正在尝试更改日历对象的时区,同时保持实际日期/时间,以便我可以在更新的日历对象上调用 getTimeInMilliseconds()。
我看了this other question。在这里,接受的答案是单独设置新日历对象的每个字段。但是,我可以通过简单地更改原始日历对象副本的时区来使其工作。奇怪的是,这只有在我在重置时区之前对原始日历进行一些修改时才有效。下面的例子说明了不一致。
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,相反,它对应于 当前日期/时间,即 2014 年 1 月 24 日 2:33:58 MTN)。谁能告诉我这里发生了什么?
编辑:刚刚更新了一些格式。
【问题讨论】:
-
@goparkyourcar 您的问题不清楚。你到底想从什么开始,你想要/期望什么作为输出?
-
目的是给定一个日历对象,该对象代表特定时区中的某个日期/时间(例如 2012 年 1 月 1 日上午 12 点 MTN),我想获得同一日期的毫秒值在另一个时区(比如 2012 年 1 月 1 日凌晨 12 点 UTC)。我对此的问题是,为什么我必须在调用我的 getUTCMilliseconds() 函数之前修改 Calendar 对象以使所述函数正常工作。
标签: java datetime calendar timezone datetime-conversion