• 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
  • 相关阅读:
    Hadoop、spark
    Hadoop、spark
    Hadoop、spark
    Hadoop、spark
    SQL查询表中的用那些索引
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    【转】迷你区块链(mini blockchain in python)
    理解 Web 3
    【转】数字货币钱包:生态及技术
    【转】用 Witnet 协议使加密网络可以跨链访问
  • 原文地址:https://www.cnblogs.com/donleo123/p/14140650.html
Copyright © 2020-2023  润新知