我正在使用以下方法将 UTC 时间转换为另一个时区:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parsed = format.parse("2011-03-01 15:10:37");
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
format.setTimeZone(tz);
String result = format.format(parsed);
所以输入是2011-03-01 15:10:37
但这个的输出(结果值)是2011-03-01 05:40:37
。虽然它看起来关闭了,并且根据这个链接 http://www.timezoneconverter.com/cgi-bin/tzc.tzc, 它应该是2011-03-01 09:10:37
.
我究竟做错了什么?
事实证明代码几乎是正确的,我没有考虑到在解析时String
得到一个Date
对象最初,它使用默认系统TimeZone
,所以源日期不是我预期的 UTC 时间。
技巧是在将日期解析为 UTC 时设置时区,然后将其设置为目的地TimeZone
。像这样的事情:
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsed = sourceFormat.parse("2011-03-01 15:10:37"); // => Date is in UTC now
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
destFormat.setTimeZone(tz);
String result = destFormat.format(parsed);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)