LocalDate/LocalDateTime/LocalTime/Date 忘是亡心i 2022-09-07 14:36 153阅读 0赞 package com.company; import java.time.*; import java.time.format.DateTimeFormatter; import java.util.Date; /** * @author xiesongzhuang1 * @Description TODO * @createTime 2021年08月20日 */ public class test { public static final LocalTime ON_HOUR_TIME = LocalTime.of(8, 0); public static final LocalTime OFF_HOUR_TIME = LocalTime.of(20, 0); public static void main(String[] args){ //Date 转LocalDate Date date = new Date(); LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); //Date 转LocalDateTime LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); //LocalDateTime转String String localDate3=date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().format(DateTimeFormatter.ofPattern("HH:mm")); System.out.println("date--"+date);//date--Mon Aug 23 16:23:48 CST 2021 System.out.println("LocalDate--"+localDate);//LocalDate--2021-08-23 System.out.println("localDateTime--"+localDateTime);//localDateTime--2021-08-23T16:40:12.962 System.out.println("LocalDate3--"+localDate3);//LocalDate2--16:37 //LocalDateTime 转Date LocalDateTime localDateTime2 = LocalDateTime.now(); Date date2 = Date.from(localDateTime.toInstant(ZoneOffset.UTC)); System.out.println("localDateTime2--"+localDateTime2);//localDateTime2--2021-08-23T20:33:15.489 System.out.println("date2--"+date2);//date2--Tue Aug 24 04:33:15 CST 2021 //LocalDateTime 转Date 标准版 Date date3= Date.from(localDateTime2.atZone(ZoneId.systemDefault()).toInstant()); System.out.println("date3-----"+date3);//date3-----Mon Aug 23 20:33:15 CST 2021 //LocalTime System.out.println(ON_HOUR_TIME);//08:00 //LocalTime到LocalDateTime LocalDateTime startLocalDate = localDate.atTime(ON_HOUR_TIME); System.out.println(startLocalDate);//2021-08-23T08:00 LocalDateTime endLocalDate=localDate.atTime(OFF_HOUR_TIME); System.out.println("endLocalDate---"+endLocalDate);//endLocalDate---2021-08-23T20:00 LocalDateTime minTime = localDate.atTime(LocalTime.MIN); LocalDateTime maxTime = localDate.atTime(LocalTime.MAX); System.out.println(minTime);//2021-08-23T00:00 System.out.println(maxTime);//2021-08-23T23:59:59.999999999 // 计算两个时间的差值LocalDateTime Duration dur = Duration.between(startLocalDate, endLocalDate); System.out.println("dur-----"+dur);//dur-----PT12H } }
还没有评论,来说两句吧...