Convert java.time.LocalDate into java.util.Date ty

2020-01-23 05:22发布

I want to convert java.time.LocalDate into java.util.Date type. Because I want to set the date into JDateChooser. Or is there any date chooser that supports java.time dates?

11条回答
欢心
2楼-- · 2020-01-23 06:06
public static Date convertToTimeZone(Date date, String tzFrom, String tzTo) {
    return Date.from(LocalDateTime.ofInstant(date.toInstant(), ZoneId.of(tzTo)).atZone(ZoneId.of(tzFrom)).toInstant());
} 
查看更多
姐就是有狂的资本
3楼-- · 2020-01-23 06:07

java.time has the Temporal interface which you can use to create Instant objects from most of the the time classes. Instant represents milliseconds on the timeline in the Epoch - the base reference for all other dates and times.

We need to convert the Date into a ZonedDateTime, with a Time and a Zone, to do the conversion:

LocalDate ldate = ...;
Instant instant = Instant.from(ldate.atStartOfDay(ZoneId.of("GMT")));
Date date = Date.from(instant);
查看更多
▲ chillily
4楼-- · 2020-01-23 06:07
java.util.Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
查看更多
我只想做你的唯一
5楼-- · 2020-01-23 06:08

Kotlin Solution:

1) Paste this extension function somewhere.

fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())

2) Use it, and never google this again.

val myDate = myLocalDate.toDate()
查看更多
仙女界的扛把子
6楼-- · 2020-01-23 06:10

Simple

public Date convertFrom(LocalDate date) {
    return java.sql.Timestamp.valueOf(date.atStartOfDay());
}
查看更多
登录 后发表回答