本文翻译自:Convert java.time.LocalDate into java.util.Date type
I want to convert java.time.LocalDate
into java.util.Date
type. 我想将java.time.LocalDate
转换为java.util.Date
类型。 Because I want to set the date into JDateChooser
. 因为我想将日期设置为JDateChooser
。 Or is there any date chooser that supports java.time
dates? 或者是否有支持java.time
日期的日期选择器?
#1楼
参考:https://stackoom.com/question/1YCwP/将java-time-LocalDate转换为java-util-Date类型
#2楼
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
假设您的日期选择器使用系统默认时区将日期转换为字符串。
#3楼
In order to create a java.util.Date from a java.time.LocalDate , you have to 要从java.time.LocalDate创建java.util.Date ,您必须这样做
- add a time to the LocalDate 为LocalDate添加时间
- interpret the date and time within a time zone 解释时区内的日期和时间
- get the number of seconds / milliseconds since epoch 获取自纪元以来的秒数/毫秒数
- create a java.util.Date 创建一个java.util.Date
The code might look as follows: 代码可能如下所示:
LocalDate localDate = LocalDate.now();
Date date = new Date(localDate.atStartOfDay(ZoneId.of("America/New_York")).toEpochSecond() * 1000);
#4楼
java.time has the Temporal interface which you can use to create Instant objects from most of the the time classes. java.time具有Temporal接口,您可以使用该接口从大多数时间类创建Instant对象。 Instant represents milliseconds on the timeline in the Epoch - the base reference for all other dates and times. Instant表示Epoch中时间轴上的毫秒数 - 所有其他日期和时间的基准参考。
We need to convert the Date into a ZonedDateTime, with a Time and a Zone, to do the conversion: 我们需要将Date转换为带有时间和区域的ZonedDateTime来进行转换:
LocalDate ldate = ...;
Instant instant = Instant.from(ldate.atStartOfDay(ZoneId.of("GMT")));
Date date = Date.from(instant);
#5楼
Here's a utility class I use to convert the newer java.time
classes to java.util.Date
objects and vice versa: 这是我用来将较新的java.time
类转换为java.util.Date
对象的实用程序类,反之亦然:
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();
}
}
Edited based on @Oliv comment. 根据@Oliv评论编辑。
#6楼
You can use java.sql.Date.valueOf()
method as: 您可以使用java.sql.Date.valueOf()
方法:
Date date = java.sql.Date.valueOf(localDate);
No need to add time and time zone info here because they are taken implicitly. 无需在此处添加时间和时区信息,因为它们是隐式使用的。
See LocalDate to java.util.Date and vice versa simpliest conversion? 请参阅LocalDate到java.util.Date,反之亦然最简单的转换?