Converting UTC dates to other timezones(将 UTC 日期转换为其他时区)
问题描述
我正在使用这种方法将 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 日期转换为其他时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 UTC 日期转换为其他时区


基础教程推荐
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- iOS4 创建后台定时器 2022-01-01