由于在 JDK8 发布以前日期类库中存在的诸多诟病,所以在 JDK8 中增加了新的日期处理类库,包含如下 package:
| |
java.time:基于ISO_8601日历系统实现的日期时间库
|
| |
java.time.chrono:全球日历系统扩展库,可以自行扩展
|
| |
java.time.format:日期时间格式,包含大量预定义的格式,可以自行扩展
|
| |
java.time.zone:时区信息库
|
| |
java.time.temporal:日期时间调整辅助库
|
新版类库不仅丰富了日期、时间抽象,而且在 API 设计上也更易理解和使用。本篇文章将主要介绍新旧日期如何实现互转。

Date 类新增了两个方法
| |
// Date 获取 Instant
|
| |
public Instant toInstant() {
|
| |
return Instant.ofEpochMilli(getTime());
|
| |
}
|
| |
|
| |
// 使用 Instant 创建 Date
|
| |
public static Date from(Instant instant) {
|
| |
try {
|
| |
return new Date(instant.toEpochMilli());
|
| |
} catch (ArithmeticException ex) {
|
| |
throw new IllegalArgumentException(ex);
|
| |
}
|
| |
}
|
使用 Date 类中新增的这两个方法,我们可以实现新旧日期类的互转。具体思路:
| |
旧转新:
|
| |
Date.toInstant() 获取 Instant,使用 Instant 创建 LocalDateTime,然后从 LocalDateTime 获取 LocalDate 和 LocalTime。
|
| |
|
| |
新转旧:
|
| |
将 LocalDate 和 LocalTime 转为 LocalDateTime,然后从 LocalDateTime 获取 Instant,使用 Date.from(Instant) 创建 Date。
|
1、Date -> LocalDateTime
| |
public static LocalDateTime dateToLocalDateTime(Date date) {
|
| |
Instant instant = date.toInstant();
|
| |
ZoneId zone = ZoneId.systemDefault();
|
| |
return LocalDateTime.ofInstant(instant, zone);
|
| |
}
|
2、Date -> LocalDate
| |
public static LocalDate dateToLocalDate(Date date) {
|
| |
LocalDateTime localDateTime = dateToLocalDateTime(date);
|
| |
return localDateTime.toLocalDate();
|
| |
}
|
3、Date -> LocalTime
| |
public static LocalTime dateToLocalTime(Date date) {
|
| |
LocalDateTime localDateTime = dateToLocalDateTime(date);
|
| |
return localDateTime.toLocalTime();
|
| |
}
|
4、LocalDateTime -> Date
| |
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
|
| |
ZoneId zone = ZoneId.systemDefault();
|
| |
Instant instant = localDateTime.atZone(zone).toInstant();
|
| |
return Date.from(instant);
|
| |
}
|
5、LocalDate -> Date
| |
public static Date localDateToDate(LocalDate localDate) {
|
| |
ZoneId zone = ZoneId.systemDefault();
|
| |
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
|
| |
return Date.from(instant);
|
| |
}
|
6、LocalTime -> Date
| |
public static Date localTimeToDate(LocalTime localTime) {
|
| |
LocalDate localDate = LocalDate.now();
|
| |
ZoneId zone = ZoneId.systemDefault();
|
| |
Instant instant = LocalDateTime.of(localDate, localTime).atZone(zone).toInstant();
|
| |
return Date.from(instant);
|
| |
}
|
继续浏览有关 Java 的文章
原文地址:https://www.caokuan.cn/index.php/archives/convertdate.html