Java8 LocalDateTime和Date相互转换

博客介绍了Java中Date与LocalDateTime的相互转换。给出了Date转LocalDateTime和LocalDateTime转Date的代码示例,还提供了DateUtils类,包含将LocalDate、LocalDateTime与Date相互转换的方法,最后给出了相关内容的来源链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很想要用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(); } }

来源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值