【问题标题】:DateFormat returning wrong hourDateFormat 返回错误的时间
【发布时间】:2018-08-20 12:44:50
【问题描述】:

我正在尝试使用DateFormat 类和"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"

下面的sn -p 打印刚才提到的日期和时间:

    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);

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

【问题讨论】:

标签: java time hour datetime-parsing


【解决方案1】:

BST 是孟加拉国标准时间。如果您想要自动夏令时,则使用的正确时区是“欧洲/伦敦”,如果您始终想要英国夏令时,则使用“UTC+1”。

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

【讨论】:

    【解决方案2】:

    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);
    

    这个 sn-p 的输出是:

    2018-08-20T13:21:00.428+01:00[欧洲/伦敦]

    你的代码出了什么问题?

    虽然我始终建议不要使用长期过时且设计不佳的类 DateTimeZoneDateFormat,但在这种情况下,它们的行为特别令人困惑。如果日期在一年中的夏季时间,则在以欧洲/伦敦作为默认时区的 JVM 上打印 Date 时区为 BST

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

    2018 年 8 月 20 日星期一 15:45:39 BST

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

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

    2018 年 8 月 20 日星期一 20:45:39 BDT

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

    另一个要学习的教训是永远不要依赖三个和四个字母的时区缩写。它们是模棱两可的,没有标准化的。

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

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

    链接

    Time Zone Abbreviations — Worldwide List

    【讨论】:

      猜你喜欢
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      相关资源
      最近更新 更多