如何将 LocalDate 转换为 SQL 日期 Java?

如何将 LocalDate 转换为 java.sql.Date

尝试:

Record r = new Record();
LocalDate date = new Date(1967, 06, 22);
r.setDateOfBirth(new Date(date));

(无法编译)失败了,我只能找到 Joda 时间的东西。

我用的是 Java 8

116906 次浏览

答案其实很简单;

import java.sql.Date;
...
LocalDate locald = LocalDate.of(1967, 06, 22);
Date date = Date.valueOf(locald); // Magic happens here!
r.setDateOfBirth(date);

如果你想把它反过来转换,你可以这样做:

Date date = r.getDate();
LocalDate localD = date.toLocalDate();

r is the record you're using in JOOQ and .getDate() is the method for getting the date out of your record; let's say you have a date column called date_of_birth, then your get method should be called getDateOfBirth().

Have you tried using the toDate() method of LocalDate?

例如:

Record r = new Record();
LocalDate date = new Date(1967, 06, 22);
r.setDateOfBirth(date.toDate());

In general, it is a good idea to specify 怎么做 it fails rather than just say "it fails".

如果你想要当前日期:

Date date = Date.valueOf(LocalDate.now());

如果你想要一个具体的日期:

Date date = Date.valueOf(LocalDate.of(1967, 06, 22));