DateFormat 返回错误的时间

DateFormat returning wrong hour

我正在尝试使用 DateFormat class 和格式模式 "dd/MM/yy' 'HH:mm:ss:SSS" 来解析字符串 "20/08/18 13:21:00:428"。时区设置为 BST。

以上返回的日期是正确的,但返回的时间为 08 小时而不是 13 - "Mon Aug 20 08:21:00 BST 2018"

以下代码片段打印了刚才提到的日期和时间:

    String toBeParsed = "20/08/18 13:21:00:428";
    DateFormat format = new SimpleDateFormat("dd/MM/yy' 'HH:mm:ss:SSS");
    format.setTimeZone(TimeZone.getTimeZone("BST"));
    Date parsedDate = format.parse(toBeParsed);
    System.out.println(parsedDate);

这与我的时区有关还是我误解了模式?

BST 是孟加拉国标准时间。如果您想要自动夏令时,则要使用的正确时区是 "Europe/London",如果您始终想要英国夏令时,则使用 "UTC+1"。

https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html#SHORT_IDS

java.time

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/uu H:mm:ss:SSS");
    String toBeParsed = "20/08/18 13:21:00:428";
    ZonedDateTime dateTime = LocalDateTime.parse(toBeParsed, formatter)
            .atZone(ZoneId.of("Europe/London"));
    System.out.println(dateTime);

此片段的输出是:

2018-08-20T13:21:00.428+01:00[Europe/London]

你的代码出了什么问题?

虽然我总是反对长期过时且设计不佳的 类 DateTimeZoneDateFormat,但在这种情况下,它们的行为特别令人困惑。在 Europe/London 作为默认时区的 JVM 上打印 Date 如果日期在一年中的夏令时部分,则时区为 BST

    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Date oldFashionedDate = new Date();
    System.out.println(oldFashionedDate);

Mon Aug 20 15:45:39 BST 2018

但是,当我将时区指定为 BST 时,孟加拉国时间是可以理解的,但它却带有非标准缩写 BDT:

    TimeZone.setDefault(TimeZone.getTimeZone("BST"));
    System.out.println(oldFashionedDate);

Mon Aug 20 20:45:39 BDT 2018

(我在 Java 8 和 Java 10 上观察到了这种行为。)

另一个要吸取的教训是永远不要依赖三个和四个字母的时区缩写。它们模棱两可且不规范。

  • BST 可能表示巴西夏令时或巴西夏令时、孟加拉国标准时间、布干维尔标准时间或英国夏令时(请注意,S 有时表示标准时间,有时表示夏季时间,这通常与标准时间相反)。
  • BDT 可能表示文莱达鲁萨兰国时间或英国夏令时(英国夏令时 (BST) 的另一个名称),但我不知道孟加拉国时间有时也这样缩写。

PS 感谢 DodgyCodeException 发现时区缩写解释问题。

Link

Time Zone Abbreviations — Worldwide List