将 ZoneId 和时间戳转换为 java 8 中的格式化日期字符串,考虑夏令时

Convert ZoneId and timestamp to formatted date string in java 8, considering daylight saving time

我有一些日志,每条日志消息都有一个时间戳,所以我想在 Java 8 中以用户友好的格式显示日志消息的时间戳,其中 java.time API.

例如,假设我有:

然后,我想将列表中的每个时间戳转换为描述我所在区域中此时间戳的字符串,因为我知道由于 DST,两个时间戳之间的偏移量 可能不同 .

我该怎么做?

java.time API's ZonedDateTime class automatically takes care of DST。因此,这是一个示例实现。

public static void main(String[] args) {
    List<Long> timestamps = new ArrayList<>();
    List<String> result = timestamps.stream()
            .map(timestamp -> convert(timestamp))
            .collect(Collectors.toCollection(ArrayList::new));
}

public static String convert(Long epochMilli) {
    Instant now = Instant.ofEpochMilli(epochMilli);
    ZoneId zoneId = ZoneId.of("Europe/Paris");
    ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, zoneId);
    DateTimeFormatter isoDateFormatter = DateTimeFormatter.ISO_DATE;
    return zonedDateTime.format(isoDateFormatter);
}