LocalDate,LocalTime,LocalDateTime,ZonedDateTime,Date
最近用到了这几个类,顺便总结一下
LocalDate,LocalTime,LocalDateTime,ZonedDateTime都是Java8+中的新增的时间类API,位于java.time包下,而Date是旧有的。
LocalDate
LocalDate表示一个日期的值(年,月,日),没有时间和时区的概念,它是不可变的(immutable),是线程安全的。可以用来存储和操作日期。
LocalTime
LocalTime表示一个时间的值(时,分,秒,纳秒),没有日期和时区的概念,它是不可变的(immutable),是线程安全的。可以用来存储和操作时间。
LocalDateTime
LocalDateTime表示一个日期时间的值(年,月,日,时,分,秒,纳秒),没有时区的概念,它是不可变的(immutable),是线程安全的。可以用来存储和操作日期时间。
ZonedDateTime
ZonedDateTime用于表示带时区信息的日期时间,其中包含了日期,时间,时区,偏移量,可以精确的表示某个特定时刻的日期和时间,是不可变的,是线程安全的。
Date
Date是java.util包下的时间日期类,非线程安全,不支持国际化和时区,不推荐使用。
LocalDate,LocalTime,LocalDateTime,Date相关代码
//当前日期
LocalDate currentDate = LocalDate.now();
System.out.println("currentDate: " + currentDate);
//当前时间
LocalTime currentTime = LocalTime.now();
System.out.println("currentTime: " + currentTime);
//当前日期和时间
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("currentDateTime: " + currentDateTime);
//Date 当前时间
Date now = new Date();
System.out.println(now);
LocalDate,LocalDateTime转为Date
//LocalDate转为Date
LocalDate currentDate = LocalDate.now();
Date localDateToDate = Date.from(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
System.out.println("localDateToDate: " + localDateToDate);
//LocalDateTime转为Date
LocalDateTime currentDateTime = LocalDateTime.now();
Date localDateTimeToDate = Date.from(currentDateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("localDateTimeToDate: " + localDateTimeToDate);
注:LocalTime不能直接转为Date
Date转为LocalDate,LocalDateTime
//Date转为LocalDate
Date now = new Date();
LocalDate dateToLocalDate = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println("dateToLocalDate: " + dateToLocalDate);
//Date转为LocalDateTime
LocalDateTime dateToLocalDateTime = LocalDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault());
System.out.println("dateToLocalDateTime: " + dateToLocalDateTime);