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()。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Spring Security放行的接口Knife4j静态资源的问题小结
这篇文章主要介绍了Spring Security使用Knife4j静态资源的问题小结,项目中使用 Spring Security 做身份认证和授权,使用 Knife4j 做接口调试,需要 Spring Security 放行的接口记录在 RequestMatcherConstant 类中,感兴趣的朋友跟随小编一起看看吧2024-02-02
java中@JSONField和@JsonProperty注解的使用说明及对比
@JSONField与@JsonProperty隶属两个不同的包,前者是阿里系的fastjson包,后者是spring boot官方使用的jackson包,本文主要介绍了java中@JSONField和@JsonProperty注解的使用说明及对比,感兴趣的可以了解一下2023-11-11
SpringBoot CommandLineRunner的异步任务机制使用
这篇文章主要介绍了SpringBoot CommandLineRunner的异步任务机制使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-08-08
详解MyBatis的getMapper()接口、resultMap标签、Alias别名、 尽量提取sql列、动态操作
这篇文章主要介绍了详解MyBatis的getMapper()接口、resultMap标签、Alias别名、 尽量提取sql列、动态操作的相关资料,需要的朋友可以参考下2016-08-08


最新评论