我有一些日志,每条日志消息都有一个时间戳,所以我想在Java 8中使用java.time
API以用户友好的格式显示日志消息的时间戳。
例如,假设我有:
List<Long>
。ZoneId
,描述了我想用来转换时间戳的区域。实际上,它是Europe/Paris
所以我必须考虑夏令时(简称DST)。DateTimeFormatter
,描述了我想要的字符串格式。然后,我想将列表中的每个时间戳转换为描述我的区域中此时间戳的字符串,因为DST知道偏移可能在两个时间戳之间。
我该怎么做?
答案 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);
}