Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert LocalDate to SQL Date Java?

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

like image 752
Gemtastic Avatar asked Mar 20 '15 14:03

Gemtastic


People also ask

Can we convert LocalDate to date in Java?

Convert LocalDate To Date in JavaStep 1: First Create the LocalDate object using either now() or of() method. now() method gets the current date where as of() creates the LocalDate object with the given year, month and day. Step 2: Next, Get the timezone from operating system using ZoneId. systemDefault() method.

What is Java sql date?

The java. sql. Date represents the date value in JDBC. The constructor of this class accepts a long value representing the desired date and creates respective Date object.

What is LocalDate NOW () in Java?

The java. time. LocalDate. now() method obtains the current date from the system clock in the default time-zone.


1 Answers

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().

like image 119
Gemtastic Avatar answered Sep 19 '22 08:09

Gemtastic