Java8中 LocalDateTime与Date互相转换

Java8 LocalDateTime与Date互相转换

1、Date转化成LocalDateTime

    /**
     * LocalDateTime与Date互相转换
     * 1、Date转化成LocalDateTime
     */
    @Test
    void testLocalDateTime(){
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();

        //方式一
        ZonedDateTime zonedDateTime = instant.atZone(zoneId);
        LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();

        //方式二 直接使用LocalDateTime.ofInstant
        LocalDateTime localDateTime1 = LocalDateTime.ofInstant(instant, zoneId);

        System.out.println("Date:" + date);
        System.out.println("LocalDateTime:" + localDateTime);
        System.out.println("localDateTime1:" + localDateTime1);
    }

运行结果:

Date:Tue Dec 15 19:53:21 CST 2020
LocalDateTime:2020-12-15T19:53:21.232
localDateTime1:2020-12-15T19:53:21.232

 

2、LocalDateTime转化成Date

     /**
     * 2、LocalDateTime转化成Date
     */
    @Test
    void testDate(){
        LocalDateTime localDateTime = LocalDateTime.now();
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
        Instant instant = zonedDateTime.toInstant();
        Date date = Date.from(instant);
        System.out.println("LocalDateTime:" + localDateTime);
        System.out.println("Date:" + date);
    }

运行结果:

LocalDateTime:2020-12-15T19:56:58.022
Date:Tue Dec 15 19:56:58 CST 2020

 

上一篇:springboot LocalDateTime 时间相关处理一个配置类就搞定了


下一篇:JPA query between的多种方式(mongodb为例)