1.第一种转换方法,借助新增类ZoneId、Instant、ZonedDateTime
public static void date2Local() { Date date = new Date(); //返回当前系统默认的时区 ZoneId zoneId = ZoneId.systemDefault(); //atZone()方法返回在指定时区,从该Instant生成的ZonedDateTime ZonedDateTime zonedDateTime = date.toInstant().atZone(zoneId); LocalDate localDate = zonedDateTime.toLocalDate(); LocalTime localTime = zonedDateTime.toLocalTime(); LocalDateTime localDateTime = zonedDateTime.toLocalDateTime(); }
2.第二种,同样使用ZoneId、Instant,但最后不同
public static void date2Local() { Date date = new Date(); ZoneId zoneId = ZoneId.systemDefault(); Instant instant = date.toInstant(); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId); LocalDate localDate = localDateTime.toLocalDate(); LocalTime localTime = localDateTime.toLocalTime(); }
3.第三种拓展,java9中新增了LocalDate、LocalTime的ofInstan()方法,所以第二种也可以写成:
public static void date2Local() { Date date = new Date(); ZoneId zoneId = ZoneId.systemDefault(); Instant instant = date.toInstant(); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId); LocalDate localDate = LocalDate.ofInstant(instant, zoneId); LocalTime localTime = LocalTime.ofInstant(instant, zoneId); }
1. java.time.LocalDateTime → java.util.Date
public void LocalDateTimeToDate() { LocalDateTime localDateTime = LocalDateTime.now(); ZoneId zoneId = ZoneId.systemDefault(); Instant instant = localDateTime.atZone(zoneId).toInstant(); Date date = Date.from(instant); }
2. java.time.LocalDate → java.util.Date
public void LocalDateToDate() { LocalDate localDate = LocalDate.now(); ZoneId zone = ZoneId.systemDefault(); //将此日期与午夜时间组合在一起,以便在此日期开始时创建LocalDateTime,即生成2017-02-03T00:00 Instant instant = localDate.atStartOfDay().atZone(zone).toInstant(); Date date = Date.from(instant); }
3. java.time.LocalTime → java.util.Date
public void LocalTimeToDate() { LocalTime localTime = LocalTime.now(); LocalDate localDate = LocalDate.now(); LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime); ZoneId zone = ZoneId.systemDefault(); Instant instant = localDateTime.atZone(zone).toInstant(); Date date = Date.from(instant); }
上一个:Kafka架构及基本原理简析
下一个:Vue动态样式:class用法