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();
        }
    }
    

    来源

  • 相关阅读:
    窗口生效函数UpdateData
    查找内容grep命令
    终止函数 atexit()
    根据名字杀死进程Killall
    修改系统时间为UTC时间
    转 proc文件
    NTP算法
    转载,网线的深刻理解
    js完成密码输入为空,和两次输入不一致
    CSS初步了解
  • 原文地址:https://www.cnblogs.com/woshimrf/p/LocalDateTime-to-Date.html
Copyright © 2011-2022 走看看