有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Java8时间库无法正确解释BST时区

这不是另一个时区问题的重复,因为我没有选择时区格式的特权。我正在迁移java代码以使用新的java8时间库,但我发现DateTimeFormatter不能正确解释时区“BST”(英国夏季时间)。它将其转换为太平洋/布干维尔时区,而不是UTC+0100。有人知道我如何修复这个问题,而不必返回到旧的SimpleDataFormat,或者使用显式设置的时区,因为我的代码需要在世界上的多个区域中运行?这个时间戳格式是通过查询另一个系统获得的,所以我无法更改它。似乎SimpleDataFormat可以正确识别时区。我的测试代码如下:

public static void main(String[] args) throws ParseException {
    String sTime = "Fri Jun 07 14:07:07 BST 2019";
    DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("EEE MMM dd kk:mm:ss z yyyy");
    ZonedDateTime zd = ZonedDateTime.parse(sTime, FORMATTER);
    System.out.println("The time zone: " + zd.getZone());
    FileTime ftReturn = FileTime.from(zd.toEpochSecond(), TimeUnit.SECONDS);
    System.out.println("File time is: " + ftReturn);

    DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
    Date dtDD = df.parse(sTime);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dtDD);
    FileTime ftReturn1 = FileTime.fromMillis(calendar.getTimeInMillis());
    System.out.println("File time1 is:  " + ftReturn1);
}

测试结果:
时区:太平洋/布干维尔
文件时间为:2019-06-07T03:07:07Z
文件时间1为:2019-06-07T13:07:07Z


共 (2) 个答案

  1. # 1 楼答案

    首先,你试图解决一个无法解决的任务。三个字母的时区缩写是模棱两可的,我想更多的时候是模棱两可的。因此,如果您为欧洲/伦敦解决了这个问题,那么当您遇到EST、IST、CST、CDT、PST、WST等时,您将再次遇到这个问题。或者,当您遇到一个字符串,其中BST表示巴西夏季时间、孟加拉国标准时间或布干维尔标准时间。还有更多的解释。取而代之的是一个明确的字符串,比如带有UTC偏移量的字符串,而不是时区缩写,最好是ISO 8601格式的字符串,比如2019-06-07T14:07:07+01:00

    但是,如果你确信英国夏令时在你的世界里永远意味着英国夏季,短视的解决方案可能是告诉DateTimeFormatter你喜欢哪个时区:

        String sTime = "Fri Jun 07 14:07:07 BST 2019";
        ZoneId preferredZone = ZoneId.of("Europe/London");
        DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
                .appendPattern("EEE MMM dd HH:mm:ss ")
                .appendZoneText(TextStyle.SHORT, Collections.singleton(preferredZone))
                .appendPattern(" yyyy")
                .toFormatter(Locale.ROOT);
        ZonedDateTime zd = ZonedDateTime.parse(sTime, FORMATTER);
        System.out.println("The time zone: " + zd.getZone());
        FileTime ftReturn = FileTime.from(zd.toEpochSecond(), TimeUnit.SECONDS);
        System.out.println("File time is: " + ftReturn);
    

    输出为:

    The time zone: Europe/London
    File time is: 2019-06-07T13:07:07Z
    

    链接