I do not know why the conversion between Date and LocalDate is so complicated and ugly. But I have to do it increasingly often. So this note is on how to convert between Date, LocalDate and milliseconds.
public static void main(String[] args) {
// convert from Date to LocalDateTime
Date d = new Date();
LocalDateTime ld = LocalDateTime.ofInstant(d.toInstant(), ZoneId.systemDefault());
// convert from LocalDateTime to Date
Date d2 = Date.from(ld.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("date : " + d);
System.out.println("ldate: " + ld);
System.out.println("date2: " + d2);
// compare milliseconds
System.out.println("millis : " + d.getTime());
System.out.println("lmillis: " + ld.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
}
The output is:
date : Sat Feb 17 14:41:00 CET 2018 ldate: 2018-02-17T14:41:00.941 date2: Sat Feb 17 14:41:00 CET 2018 millis : 1518874860941 lmillis: 1518874860941
No comments:
Post a Comment