我想将日期(以毫秒为单位)转换为日期,但无法正确转换。
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
todayBack:---------- 1970-01-18
答案 0 :(得分:6)
您需要使用ofEpochSecond
代替ofEpochMilli
,因为todayLong
为second
,而不是milisecond
LocalDate todayBack = Instant.ofEpochSecond(todayLong).atZone(ZoneId.systemDefault()).toLocalDate();
答案 1 :(得分:2)
你在第6行(Instant.ofEpochMilli
)有一点错误。
请改用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);
答案 2 :(得分: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