将UTC日期转换为其他时区

将UTC日期转换为其他时区

本文介绍了将UTC日期转换为其他时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  SimpleDateFormat format = new SimpleDateFormat(yyyy -MM-ddHH: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



我做错了什么?

解决方案

事实证明,代码几乎正确,我没有考虑到的是在解析 String 最初获得 Date 对象,它使用默认系统 TimeZone ,所以源日期不在UTC正如我预期的那样。



诀窍是在将日期解析为UTC时设置时区,然后将其设置为目标 TimeZone 。这样的东西:

  SimpleDateFormat sourceFormat = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss); 
sourceFormat.setTimeZone(TimeZone.getTimeZone(UTC));
日期解析= sourceFormat.parse(2011-03-01 15:10:37); // =>日期在UTC现在

TimeZone tz = TimeZone.getTimeZone(America / Chicago);
SimpleDateFormat destFormat = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);
destFormat.setTimeZone(tz);

String result = destFormat.format(parsed);


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);

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.

What am I doing wrong?

解决方案

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.

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

07-27 23:21