将UTC日期/时间显示为当前时区的日期/时间

8

我从网络中获取了一个日期/时间字符串,格式为 "yyyy/mm/dd'T'HH:MM:SS'Z'",它是以UTC时区表示的。

现在我需要确定设备当前所处的时区,然后将此时间转换为本地时间。

我该怎么做?

(FYI,目前UTC时间是上午10:25,在印度当前时间是下午3:55)

1个回答

14
尝试使用TimeZone.getDefault()代替TimeZone.getTimeZone("GMT")
文档中得知:
“…您可以使用getDefault创建一个基于程序运行所在时区的TimeZone。”
编辑:您可以使用SimpleDateFormat解析日期(该处还提供了格式字符串的文档)。 在您的情况下,您需要执行以下操作(未经测试):
 // note that I modified the format string slightly
 SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd'T'HH:mm:ss'Z'");
 // set the timezone to the original date string's timezone
 fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
 Date date = fmt.parse("1998/12/21T13:29:31Z", new ParsePosition(0));

 // then reset to the target date string's (local) timezone
 fmt.setTimeZone(TimeZone.getDefault());
 String localTime = fmt.format(date);

或者,使用两个单独的SimpleDateFormat实例,一个用于原始时间,另一个用于目标时间。


@Lei Ryan,亲爱的,我知道如何解析和格式化日期,但想要将UTC显示为本地时区。 - Paresh Mayani
@Paresh Mayani:你应该在问题中说明。请查看我的更新答案。 - Lie Ryan
@Lei Ryan 这个可行了!!找到你之前的答案非常有帮助,我按照你的代码写了一样的。顺便说一下,谢谢你的快速回复和支持。 - Paresh Mayani
你确定你有正确的格式吗?mm代表分钟,MM代表月份。在年和天之间加上分钟会看起来非常奇怪。 - NickT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接