gpt4 book ai didi

java - BST 时间错误

转载 作者:行者123 更新时间:2023-12-02 02:14:30 27 4
gpt4 key购买 nike

使用下面的代码,每个时区都正确打印值,除了 BST

​import java.text.*;

def format = "yyyy-MM-dd HH:mm:ssXXX"
def dt = new Date();
println dt;

SimpleDateFormat utcFormat = new SimpleDateFormat(format)
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"))
println utcFormat.format(dt)

SimpleDateFormat istFormat = new SimpleDateFormat(format)
istFormat .setTimeZone(TimeZone.getTimeZone("IST"))
println istFormat.format(dt)

SimpleDateFormat cetFormat = new SimpleDateFormat(format)
cetFormat.setTimeZone(TimeZone.getTimeZone("CET"))
println cetFormat.format(dt)

SimpleDateFormat bstFormat = new SimpleDateFormat(format)
bstFormat.setTimeZone(TimeZone.getTimeZone("BST"))
println bstFormat.format(dt)

输出:

2018 年 3 月 26 日星期一 09:04:14 世界标准时间

2018-03-26 09:04:14Z

2018-03-26 14:34:14+05:30

2018-03-26 11:04:14+02:00

2018-03-26 15:04:14+06:00

此处 BST 时间错误。有什么问题吗?

最佳答案

您应该避免使用缩写的时区名称。检查 TimeZone documentation 中的以下注释:

Three-letter time zone IDs

For compatibility with JDK 1.1.x, some other three-letter time zoneIDs (such as "PST", "CTT", "AST") are also supported. However, theiruse is deprecated because the same abbreviation is often used formultiple time zones (for example, "CST" could be U.S. "CentralStandard Time" and "China Standard Time"), and the Java platform canthen only recognize one of them.

就您的情况而言,系统可能已将 BST 映射到 比什凯克标准时间,其时区偏移为 +06:00 小时。标准命名约定是地区/城市,例如欧洲/伦敦、欧洲/巴黎、亚洲/加尔各答等。其中城市通常指该地区某个国家/地区最大的城市。如有疑问,请执行以下语句来获取所有时区 ID:

System.out.println(ZoneId.getAvailableZoneIds());

java.time

java.util Date-Time API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用并切换到 modern Date-Time API *

使用现代日期时间 API java.time 的解决方案:

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
public static void main(String args[]) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ssXXX", Locale.ENGLISH);

Instant now = Instant.now();

System.out.println(now.atZone(ZoneOffset.UTC).format(dtf));
System.out.println(now.atZone(ZoneId.of("Asia/Kolkata")).format(dtf));
System.out.println(now.atZone(ZoneId.of("Europe/Paris")).format(dtf));
System.out.println(now.atZone(ZoneId.of("Europe/London")).format(dtf));
}
}

输出样本运行:

2021-10-12 12:24:03Z
2021-10-12 17:54:03+05:30
2021-10-12 14:24:03+02:00
2021-10-12 13:24:03+01:00

ONLINE DEMO

Trail: Date Time 了解有关现代日期时间 API 的更多信息

<小时/>

* 如果您正在处理 Android 项目,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 。请注意,Android 8.0 Oreo 已经提供 support for java.time

关于java - BST 时间错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49487752/

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