gpt4 book ai didi

java - 根据当前时区将 UTC 日期/时间显示为日期/时间

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:19:11 27 4
gpt4 key购买 nike

我从网络上获取格式为“yyyy/mm/dd'T'HH:MM:SS'Z'”的日期/时间字符串,它是 UTC。

现在我必须识别设备的当前时区,然后将这个时间转换为我的本地时间..

我该怎么做?

(仅供引用,目前,UTC 时间是上午 10:25,印度当前时间是下午 3:55)

最佳答案

尝试使用 TimeZone.getDefault() 而不是 TimeZone.getTimeZone("GMT")

来自 the docs :

... you get a TimeZone using getDefault which creates a TimeZone based on the time zone where the program is running.

编辑:您可以使用 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 实例,一个用于原始时间,一个用于目标时间。

关于java - 根据当前时区将 UTC 日期/时间显示为日期/时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4068132/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com