Date、LocalDate、LocalDateTime、Instant相互转换

 本文用到了Instant 时间戳类,可以通过Instant.now()获取到当前更精准的毫秒值,相当于System.currentTimeMillis()获取到毫秒,但是instant可以精准纳秒。

Java8里新特性  Instant可以作为LocalDateTime和Date之间转换的中间商。

Date包含了时间和日期,LocalDate只包含了日期,LocalDateTime包含了日期和时间

 转换思路:

Date--> Instant--> ZonedDateTime--> LocalDate / LocalDateTime

//Date转为LocalDate
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//获取一个时间
Date date = dateFormat.parse("2023-11-18 10:07:00");

//把Date转为Instant Instant时区是UTC
Instant toInstant = date.toInstant();
System.out.println("instant: "+toInstant);
System.out.println("GMT+8后的instant: "+toInstant.atOffset(ZoneOffset.ofHours(8)));

//Date 转成 LocalDateTime
LocalDateTime localDateTime =  date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println("Date转换成LocalDateTime: "+localDateTime);

//Date 转成 LocalDate
LocalDate localDate =  date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println("date 转成 LocalDate: "+localDate);

//LocalDateTime 转成 Date
Instant instant  = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date date1 = Date.from(instant);
System.out.println("LocalDateTime 转成 Date: "+date1);

//LocalDate 转成 Date
LocalDateTime localDateTime1 = localDate.atStartOfDay();
Instant instant1 = localDateTime1.atZone(ZoneId.systemDefault()).toInstant();
Date date2 = Date.from(instant1);
System.out.println("LocalDate 转成 Date: "+ date2);

//LocalDateTime 格式化
String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("LocalDateTime格式化: "+format);

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值