我正在使用这种方法将 UTC 时间转换为另一个时区:
I'm converting a UTC time to another timezone, using this method:
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
代码>.虽然它似乎关闭,但根据 此链接,它应该是 2011-03-01 09:10:37
.
So the input is 2011-03-01 15:10:37
but the output of this (value of result) is 2011-03-01 05:40:37
. While it seems off, and according to this link, it should be 2011-03-01 09:10:37
.
我做错了什么?
原来代码几乎是正确的,我没有考虑到在解析 String
时得到一个Date
对象最初,它使用默认系统 TimeZone
,所以源日期不是我预期的 UTC.
It turns out the code was almost correct, what I didn't take into account was that when parsing the String
to get a Date
object initially, it uses default system TimeZone
, so the source date was not in UTC as I expected.
诀窍是在将日期解析为 UTC 时设置时区,然后将其设置为目标 TimeZone
.像这样的:
The trick was to set the timezone when parsing the date to UTC and then set it to destination TimeZone
. Something like this:
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);
这篇关于将 UTC 日期转换为其他时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!