java Date实现转成LocalDate和LocalTime,LocalDateTime
在Java中,java.util.Date 代表了自“the epoch”(即1970年1月1日 00:00:00 GMT)以来的毫秒数。而java.time包(Java 8及以后版本)中的LocalDate、LocalTime和LocalDateTime则提供了更为丰富和直观的日期时间API。
要将java.util.Date转换为LocalDate、LocalTime或LocalDateTime,可以使用java.time.Instant类作为中间桥梁,因为Instant类可以表示时间线上的一个瞬时点,与java.util.Date有相似的用途(尽管Instant是以UTC表示的,而Date是相对于默认时区的)。
Date 转 LocalDate
import java.util.Date;
import java.time.LocalDate;
import java.time.Instant;
import java.time.ZoneId;
public class DateToLocalDate {
public static void main(String[] args) {
Date date = new Date(); // 获取当前日期时间
// 转换为Instant
Instant instant = date.toInstant();
// 转换为LocalDate,需要指定时区,因为LocalDate不包含时区信息
// 这里使用系统默认时区
LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println("LocalDate: " + localDate);
}
}Date 转 LocalTime
import java.util.Date;
import java.time.LocalTime;
import java.time.Instant;
import java.time.ZoneId;
public class DateToLocalTime {
public static void main(String[] args) {
Date date = new Date(); // 获取当前日期时间
// 转换为Instant
Instant instant = date.toInstant();
// 转换为LocalTime,需要指定时区
LocalTime localTime = instant.atZone(ZoneId.systemDefault()).toLocalTime();
System.out.println("LocalTime: " + localTime);
}
}Date 转 LocalDateTime
import java.util.Date;
import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;
public class DateToLocalDateTime {
public static void main(String[] args) {
Date date = new Date(); // 获取当前日期时间
// 转换为Instant
Instant instant = date.toInstant();
// 转换为LocalDateTime,需要指定时区
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println("LocalDateTime: " + localDateTime);
}
}在上述示例中,首先将java.util.Date对象转换为java.time.Instant,然后通过atZone(ZoneId.systemDefault())方法将其转换为特定时区(这里是系统默认时区)的ZonedDateTime对象。由于LocalDate、LocalTime和LocalDateTime都是时区无关的(对于LocalDateTime来说,它实际上是“本地”的,不包含时区信息,但在这里通过指定时区来从Instant获取它),最后通过调用.toLocalDate()、.toLocalTime()或.toLocalDateTime()方法将它们从ZonedDateTime中提取出来。
注意:
在转换过程中,需要指定一个时区,因为java.util.Date本身并不包含时区信息,它只是自epoch以来的毫秒数。因此,在转换为LocalDate、LocalTime或LocalDateTime时,需要明确想要哪个时区的日期或时间。
如果想要的是UTC时间,你可以使用ZoneId.of("UTC")代替ZoneId.systemDefault()。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
SpringBoot使用Docx4j实现DOCX转PDF功能
在当今的企业级应用中,文档格式转换是一个高频但又容易被低估的需求,从合同签署、报表生成到知识库管理,DOCX转PDF的需求无处不在,今天我们就介绍一款使用纯Java实现 DOCX 转 PDF的方案,超级简单,简直不要太爽,需要的朋友可以参考下2026-02-02
IntelliJ IDEA语法报错"Usage of API documented as @since 1.6+"的解决
今天小编就为大家分享一篇关于IntelliJ IDEA语法报错"Usage of API documented as @since 1.6+"的解决办法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧2018-10-10
IDEA连接MySQL提示serverTimezone的问题及解决方法
很多朋友私聊小编,使用IDEA软件连接MySQL数据库时总是提示Server returns invalid timezone. Go to 'Advanced' tab and set 'serverTimezone' property manually.的错误,小编就不一一回复大家了,下面小编把我的解决方法分享到脚本之家平台,需要的朋友参考下吧2021-05-05
idea创建springboot项目和springcloud项目的详细教程
这篇文章主要介绍了idea创建springboot项目和springcloud项目方法,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-10-10


最新评论