2

我想以毫秒为单位将日期转换为日期,但转换不正确。

public static void main(String[] args) {        
    LocalDate today = LocalDateTime.now().toLocalDate();
    System.out.println("Today: ----------" + today);
    long todayLong = today.atStartOfDay(ZoneId.systemDefault()).toEpochSecond();
    System.out.println("todayLong: ---------- " + todayLong);
    LocalDate todayBack = Instant.ofEpochMilli(todayLong).atZone(ZoneId.systemDefault()).toLocalDate();
    System.out.println("todayBack: ---------- "+todayBack);
}

这是输出:

今天:---------2017-06-27

今天长: ---------- 1498507200

今天返回: ---------- 1970-01-18

4

3 回答 3

10

您需要使用ofEpochSecond而不是ofEpochMilli因为您的todayLongis second,而不是milisecond

LocalDate todayBack = Instant.ofEpochSecond(todayLong).atZone(ZoneId.systemDefault()).toLocalDate();
于 2017-06-27T09:19:25.347 回答
2

Instant.ofEpochMilli您在第 6 行 ( )处有一个小错误。改用Instant.ofEpochSecond

LocalDate today = LocalDateTime.now().toLocalDate();
System.out.println("Today: ----------" + today);
long todayLong = today.atStartOfDay(ZoneId.systemDefault()).toEpochSecond();
System.out.println("todayLong: ---------- " + todayLong);
LocalDate todayBack = Instant.ofEpochSecond(todayLong).atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println("todayBack: ---------- " + todayBack);
于 2017-06-27T09:23:00.903 回答
1

你必须将 todayLong 乘以 1000

LocalDate todayBack = Instant.ofEpochMilli(todayLong * 1000).atZone(ZoneId.systemDefault()).toLocalDate();

System.out.println("todayBack: ---------- " + todayBack);

获得输出:

今天:---------2017-06-27

今天长: ---------- 1498514400

今天返回: ---------- 2017-06-27

于 2017-06-27T09:17:56.457 回答