如何将 LocalDate 转换为 SQL Date Java?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29168494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert LocalDate to SQL Date Java?
提问by Gemtastic
How do I convert a LocalDate to a java.sql.Date
?
如何将 LocalDate 转换为java.sql.Date
?
Attempt:
试图:
Record r = new Record();
LocalDate date = new Date(1967, 06, 22);
r.setDateOfBirth(new Date(date));
This fails (won't compile)and all I can find is Joda time stuff.
这失败了(不会编译),我能找到的只是 Joda 时间的东西。
I'm using Java 8
我正在使用 Java 8
采纳答案by Gemtastic
The answer is really simple;
答案很简单;
import java.sql.Date;
...
LocalDate locald = LocalDate.of(1967, 06, 22);
Date date = Date.valueOf(locald); // Magic happens here!
r.setDateOfBirth(date);
If you would want to convert it the other way around, you do it like this:
如果你想反过来转换它,你可以这样做:
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()
.
r
是您在 JOOQ 中使用的记录,是从记录.getDate()
中获取日期的方法;假设您有一个名为 date_of_birth 的日期列,那么您的 get 方法应该被调用getDateOfBirth()
。
回答by juhist
Have you tried using the toDate() method of LocalDate?
您是否尝试过使用 LocalDate 的 toDate() 方法?
As in:
如:
Record r = new Record();
LocalDate date = new Date(1967, 06, 22);
r.setDateOfBirth(date.toDate());
In general, it is a good idea to specify howit fails rather than just say "it fails".
一般来说,最好说明它是如何失败的,而不是仅仅说“它失败了”。
回答by RichardK
If you want current date:
如果您想要当前日期:
Date date = Date.valueOf(LocalDate.now());
If you want a specific date:
如果你想要一个特定的日期:
Date date = Date.valueOf(LocalDate.of(1967, 06, 22));