Java8的Date和LocalDateTime互相转换

 /**
     * Date转换为LocalDateTime
     */
    private static void test2() {
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        System.out.println(localDateTime);//2019-11-04T14:33:29.942
		//合并
        LocalDateTime time = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

        //方法二:
        LocalDateTime localDateTime2 = LocalDateTime.ofInstant(instant, zoneId);
        System.out.println(localDateTime2);//Mon Nov 04 14:43:30 CST 2019
    }
/**
     * LocalDateTime转换为Date
     */
    private static void test3() {
        LocalDateTime localDateTime = LocalDateTime.now();
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
        Date date = Date.from(zonedDateTime.toInstant());
        System.out.println(date.toString());//Mon Nov 04 14:41:33 CST 2019

        //合并
        Date date2 = Date.from(localDateTime.atZone(zoneId).toInstant());
    }

你可能感兴趣的:(Java)