转换 ZONES 时 Java SimpleDateFormat 的问题

问题描述 投票:0回答:1

我有一个类似的方法

public String format(long epochTimeInMS, String timeZone) {
    Date d = new Date(epochTimeInMS);
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm z");
    formatter.setTimeZone(TimeZone.getTimeZone(timeZone));
    return formatter.format(date);
  }

它曾经为值 1715752155000L、“PST”返回“22:49 PDT”,这是预期的行为。我使用的是 jdk 8。升级到 jdk 17 后,该方法返回“21:41 GMT-08:00”。你能帮忙吗?

java java-17
1个回答
0
投票

使用

java.time
包的解决方案是推荐的方式。有趣的是,“PST”不是有效的时区,尽管
DateTimeFormatter
可以发出它。相反,我使用了时区中的有效城市。由于当前夏令时,输出具有“PDT”,这也与我从
SimpleDateFormat
得到的结果相同。

import java.time.*;
import java.time.format.*;

public class Main {
    public static void main(String[] args) {
      
    long epochTimeInMS=1715752155000L;
  
    ZonedDateTime zonedDateTime = Instant.ofEpochMilli(epochTimeInMS)
          .atZone(ZoneId.of("America/Los_Angeles"));
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm z");
    String formattedString = zonedDateTime.format(dateTimeFormatter);
        
    System.out.println("ZonedDateTime: "+ formattedString);
  }
}

输出:

ZonedDateTime: 22:49 PDT
© www.soinside.com 2019 - 2024. All rights reserved.