0%

java LocalDateTime转Unix timestamp

现在尽量使用新的API,把Date换成LocalDateTime。

使用LocalDateTime时,我们可以通过如下方法把LocalDateTime转换为Unix Timestamp。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
System.out.println(System.currentTimeMillis());
System.out.println(now.toEpochSecond(ZoneOffset.of("+8")));
System.out.println(now.toInstant(ZoneOffset.of("+8")).toEpochMilli());
System.out.println(now.toInstant(ZoneOffset.UTC).toEpochMilli());
System.out.println(now.plusDays(1).toInstant(ZoneOffset.of("+8")).toEpochMilli());
}

2021-03-10T13:45:39.411
1615355139422
1615355139
1615355139411
1615383939411
1615441539411

LocalDateTime格式化为指定格式:

1
2
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd hh:mm:ss");
String timeStr = LocalDateTime.now().atZone(ZoneOffset.of("+8")).format(formatter);

举个例子,假如我要显示当前时间往后推4小时后,UTC的时间表示。

1
2
3
LocalDateTime now = LocalDateTime.now();
ZonedDateTime zonedDateTime = now.plusHours(4).atZone(ZoneOffset.ofHours(8));
String future = zonedDateTime.withZoneSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("YYYY-MM-dd hh:mm:ss"));