How do I convert a LocalDate to a 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.
I'm using Java 8
How do I convert a LocalDate to a 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.
I'm using Java 8
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()
.
java.util.Date
NOT java.sql.Date
which this Question is about. –
Pressurize 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));
Date date = Date.valueOf(LocalDate.of(1967, 06, 22));
if you want to do it "faster". –
Pressurize Have you tried using the toDate() method of LocalDate?
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 how it fails rather than just say "it fails".
getDate()
is deprecated since Java 1.1 –
Thermic © 2022 - 2024 — McMap. All rights reserved.
java.sql.Date
even though that class was always a hack on top of the already poorly designedjava.util.Date
class. Since the advent of JDBC 4.2 and Hibernate 5, just store yourLocalDate
directly into your database and forget that the two problematicDate
classes ever existed. – Pazit