您的位置:

Java DateTime转Date

一、DateTime类与Date类的概述

Java中的DateTime类和Date类都是用来表示日期和时间的类,但是它们之间有很大的不同。

DateTime类是Java8中新增的一个时间日期API,它是线程安全的,同时提供了许多处理日期和时间的方法。Date类,是Java早期版本中就有的,但是它不是线程安全的,并且大多数方法已经被废弃了,因此在实际项目中不建议使用。

二、DateTime转Date的方法

在Java中,将DateTime对象转换为Date对象的方法有很多,下面介绍几种比较常用的方法。

1、使用toInstant()方法

DateTime类中提供了toInstant()方法,可以将当前的DateTime对象转换为Instant对象,再通过Date.from()方法转换为Date对象。


// 获取当前时间
LocalDateTime now = LocalDateTime.now();
// 将当前时间转换为 Instant 对象
Instant instant = now.toInstant(ZoneOffset.of("+8"));
// 转换为 Date 对象
Date date = Date.from(instant);
System.out.println(date);

2、使用atZone()方法

DateTime类中提供了atZone()方法,可以将当前的DateTime对象转换为ZoneDateTime对象,再通过toInstant()方法转换为Instant对象,最后通过Date.from()方法转换为Date对象。


// 获取当前时间
LocalDateTime now = LocalDateTime.now();
// 转换为带时区的时间
ZonedDateTime zonedDateTime = now.atZone(ZoneId.systemDefault());
// 转换为 Instant 对象
Instant instant = zonedDateTime.toInstant();
// 转换为 Date 对象
Date date = Date.from(instant);
System.out.println(date);

3、使用Calendar类

另外一种方法是使用Calendar类,可将DateTime对象先转换为LocalDateTime对象,再逐个获取年月日时分秒,最后使用Calendar来设置时间。


// 获取当前时间
LocalDateTime now = LocalDateTime.now();
// 转换为LocalDateTime对象
LocalDateTime localDateTime = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), now.getHour(), now.getMinute(), now.getSecond());
// 使用Calendar类
Calendar calendar = Calendar.getInstance();
calendar.set(localDateTime.getYear(), localDateTime.getMonthValue()-1, localDateTime.getDayOfMonth(), localDateTime.getHour(), localDateTime.getMinute(), localDateTime.getSecond());
Date date = calendar.getTime();
System.out.println(date);

三、DateTime与Date的转换小结

以上介绍了Java中将DateTime对象转换为Date对象的三种方法:使用toInstant()方法、使用atZone()方法和使用Calendar类。

相比起来,toInstant()方法和atZone()方法更加直观,而且日期的转换明确,不容易出错。而使用Calendar类的方法则比较繁琐,需要逐个获取年月日时分秒,但是在某些特殊场合,例如需要设置毫秒数的时候,则可以按照此方式进行处理。