gpt4 book ai didi

java - GMT 以错误的方式转换为本地隐蔽(错误值)

转载 作者:行者123 更新时间:2023-11-29 15:43:28 24 4
gpt4 key购买 nike

我有以下将 GMT 时间转换为本地时间的代码,我从 StackOverflow 上的一个答案中获取它,问题是此代码返回 GMT 时间的错误值。

我的 GMT 时间是:+3,但代码使用的是 +2,我猜它从我的设备中获取 GMT 时间,而我设备的时间是 +3 GMT。

代码如下:

        String inputText = "12:00";
SimpleDateFormat inputFormat = new SimpleDateFormat
("kk:mm", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat outputFormat =
new SimpleDateFormat("kk:mm");
// Adjust locale and zone appropriately
Date date = null;
try {
date = inputFormat.parse(inputText);
} catch (ParseException e) {
e.printStackTrace();
}
String outputText = outputFormat.format(date);
Log.i("Time","Time Is: " + outputText);

日志返回:14:00

最佳答案

这与您进行转换的日期有关。

您只指定了小时和分钟,因此计算是在 1970 年 1 月 1 日完成的。在该日期,您所在时区的 GMT 偏移大概只有 2 小时。

也指定日期。


SimpleDateFormat inputFormat =
new SimpleDateFormat("kk:mm", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat outputFormat =
new SimpleDateFormat("yyyy/MM/dd kk:mm", Locale.US);
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

Date date = inputFormat.parse("12:00");

System.out.println("Time Is: " + outputFormat.format(date));

Ideone demo

输出:

Time Is: 1970/01/01 12:00

显示夏令时/夏令时影响的附加代码:

SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyy/MM/dd kk:mm", Locale.US);
gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat finlandFormat = new SimpleDateFormat("yyyy/MM/dd kk:mm zzz", Locale.US);
finlandFormat.setTimeZone(TimeZone.getTimeZone("Europe/Helsinki"));

SimpleDateFormat plus3Format = new SimpleDateFormat("yyyy/MM/dd kk:mm zzz", Locale.US);
plus3Format.setTimeZone(TimeZone.getTimeZone("GMT+3"));

Date date = gmtFormat.parse("1970/01/01 12:00");
System.out.println("Time Is: " + gmtFormat.format(date));
System.out.println("Time Is: " + finlandFormat.format(date));
System.out.println("Time Is: " + plus3Format.format(date));

date = gmtFormat.parse("2016/04/22 12:00");
System.out.println("Time Is: " + gmtFormat.format(date));
System.out.println("Time Is: " + finlandFormat.format(date));
System.out.println("Time Is: " + plus3Format.format(date));

输出:

Time Is: 1970/01/01 12:00
Time Is: 1970/01/01 14:00 EET <-- Eastern European Time
Time Is: 1970/01/01 15:00 GMT+03:00
Time Is: 2016/04/22 12:00
Time Is: 2016/04/22 15:00 EEST <-- Eastern European Summer Time
Time Is: 2016/04/22 15:00 GMT+03:00

关于java - GMT 以错误的方式转换为本地隐蔽(错误值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36803428/

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