考虑夏令时

时间:2017-11-03 13:02:25

标签: java timezone dst java-time datetimeoffset

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

例如,假设我有:

  • 存储我所有日志时间戳的List<Long>
  • 一个ZoneId,描述了我想用来转换时间戳的区域。实际上,它是Europe/Paris所以我必须考虑夏令时(简称DST)。
  • 一个DateTimeFormatter,描述了我想要的字符串格式。

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

我该怎么做?

1 个答案:

答案 0 :(得分:4)

java.time API的ZonedDateTime课程会自动处理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);
}