本文用到了Instant 时间戳类,可以通过Instant.now()获取到当前更精准的毫秒值,相当于System.currentTimeMillis()获取到毫秒,但是instant可以精准纳秒。
Java8里新特性 Instant可以作为LocalDateTime和Date之间转换的中间商。
Date包含了时间和日期,LocalDate只包含了日期,LocalDateTime包含了日期和时间
转换思路:
Date--> Instant--> ZonedDateTime--> LocalDate / LocalDateTime
//Date转为LocalDate
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//获取一个时间
Date date = dateFormat.parse("2023-11-18 10:07:00");
//把Date转为Instant Instant时区是UTC
Instant toInstant = date.toInstant();
System.out.println("instant: "+toInstant);
System.out.println("GMT+8后的instant: "+toInstant.atOffset(ZoneOffset.ofHours(8)));
//Date 转成 LocalDateTime
LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println("Date转换成LocalDateTime: "+localDateTime);
//Date 转成 LocalDate
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println("date 转成 LocalDate: "+localDate);
//LocalDateTime 转成 Date
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date date1 = Date.from(instant);
System.out.println("LocalDateTime 转成 Date: "+date1);
//LocalDate 转成 Date
LocalDateTime localDateTime1 = localDate.atStartOfDay();
Instant instant1 = localDateTime1.atZone(ZoneId.systemDefault()).toInstant();
Date date2 = Date.from(instant1);
System.out.println("LocalDate 转成 Date: "+ date2);
//LocalDateTime 格式化
String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("LocalDateTime格式化: "+format);