转换UTC日期其他时区 [英] Converting UTC dates to other timezones

查看:165
本文介绍了转换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五点四十零分37秒。虽然看起来关闭,并根据此链接时,它应 2011- 03-01 9时十分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.

我是什么做错了吗?

推荐答案

原来,code几乎是正确的,什么我没考虑到的是,在解析字符串时,获得日期对象最初,它使用默认的系统时区,因此源日期为没有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时,设置时区,然后将其设置为目的地时区。事情是这样的:

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 = format.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日期其他时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆