zoukankan      html  css  js  c++  java
  • Java8 LocalDateTime和Date相互转换

    很想要用Java的时间api,但有时候还是需要转换为Date. 二者的相互转换并不是一步到位那么简单,所以,还是需要记录一下转换的api

    Date to LocalDateTime

    Date todayDate = new Date();
    
    LocalDateTime ldt = todayDate.toInstant()
            .atZone( ZoneId.systemDefault() )
            .toLocalDateTime();
    
    System.out.println(ldt);
    //2019-05-16T19:22:12.773
    

    LocalDateTime to Date

    LocalDateTime localDateTime = LocalDateTime.now();
    
    Date date = Date.from( localDateTime.atZone( ZoneId.systemDefault()).toInstant());
    
    System.out.println(date);
    //Thu May 16 19:22:37 CST 2019
    

    DateUtils

    import java.time.Instant;
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.ZoneId;
    import java.util.Date;
     
    public class DateUtils {
     
        public static Date asDate(LocalDate localDate) {
            return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
        }
     
        public static Date asDate(LocalDateTime localDateTime) {
            return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        }
     
        public static LocalDate asLocalDate(Date date) {
            return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
        }
     
        public static LocalDateTime asLocalDateTime(Date date) {
            return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
        }
    }
    

    来源

  • 相关阅读:
    STM32Cube Uart_DMA测试工程
    STM32CubeMX安装指南
    基于STM32Cube的ADC模数采样设计
    C++ this指针的用法
    用七段数码管显示26个字母的方案
    FPGA的引脚VCCINT 、VCCIO VCCA
    Keil环境中建立带FreeRTOS的STM32L项目
    STM32L时钟
    Mysql explain
    nginx屏蔽IP
  • 原文地址:https://www.cnblogs.com/woshimrf/p/LocalDateTime-to-Date.html
Copyright © 2011-2022 走看看