我有一个类似的方法
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.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