【发布时间】:2010-11-01 10:32:51
【问题描述】:
我从 Web 获取格式为“yyyy/mm/dd'T'HH:MM:SS'Z'”的日期/时间字符串,它采用 UTC。
现在我必须识别设备的当前时区,然后将这个时间转换为我的本地时间..
我该怎么做,请建议我!!
(仅供参考,目前,UTC 时间是上午 10:25,在印度当前时间是下午 3:55)
【问题讨论】:
我从 Web 获取格式为“yyyy/mm/dd'T'HH:MM:SS'Z'”的日期/时间字符串,它采用 UTC。
现在我必须识别设备的当前时区,然后将这个时间转换为我的本地时间..
我该怎么做,请建议我!!
(仅供参考,目前,UTC 时间是上午 10:25,在印度当前时间是下午 3:55)
【问题讨论】:
尝试使用TimeZone.getDefault() 而不是TimeZone.getTimeZone("GMT")
来自the docs:
...你得到一个 TimeZone 使用 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 实例,一个用于原始时间,一个用于目标时间。
【讨论】: