栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LocalDateTime ,Date 互转

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LocalDateTime ,Date 互转

JDK1.8中LocalDateTime 与 Date  通过 Instant(瞬时 即时) 进行互转

具体可用查看 Date 与  LocalDateTime 源码
主要方法:

// Date 源码主要方法
public static Date from(Instant instant) {
        try {
            return new Date(instant.toEpochMilli());
        } catch (ArithmeticException ex) {
            throw new IllegalArgumentException(ex);
        }
    }

 public Instant toInstant() {
        return Instant.ofEpochMilli(getTime());
    }

//LocalDateTime 源码主要方法

  public ZonedDateTime atZone(ZoneId zone) {
        return ZonedDateTime.of(this, zone);
    }

 default Instant toInstant() {
        return Instant.ofEpochSecond(toEpochSecond(), toLocalTime().getNano());
    }

Date 源码 

Date.from()
 
    public static Date from(Instant instant) {
        try {
            return new Date(instant.toEpochMilli());
        } catch (ArithmeticException ex) {
            throw new IllegalArgumentException(ex);
        }
    }

demo

 //        LocalDateTime 转 Date 
        LocalDateTime localDateTime = LocalDateTime.now();
        Date date2 = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(date2));

        // Date 转 LocalDate

        Date date3 = new Date();
        LocalDateTime localDateTime1 = 
        date3.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        System.out.println(localDateTime1);

String 转 Date
 

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// String 转 Date
Date date6 = format.parse("2022-06-14 15:28:04");
System.out.println("SimpleDateFormat String 转 Date :" + date6);

// 时间戳(毫秒 ) 转 日期格式
// 时间戳转 Date 直接 new Date(时间戳)
 Date date5 = new Date(1655192442000L)

// Date 转 String
  String data5Str = format.format(date5);

System.out.println("时间戳:"+data5Str);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/975661.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号