How to save a localdate in a mysql table?

2

I have a table book that has a column of type "Date" and in my java code I have a field of type "localdate". I need to save the data from the "LocalDate" field in the table however I am finding it difficult to do this, any suggestions?

Java:

package servico;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import model.Livro;


public class LivroService {
    private List<Livro> listaLivros;
    SimpleDateFormat sdt = new SimpleDateFormat("dd-MM-yyyy");

    public LivroService() {
        listaLivros = new ArrayList<>();
        listaLivros.add(new Livro(1,123456,"Harry Potter","J.K Rowling","HP",sdt.format("12-10-2015")));
    }

}
    
asked by anonymous 25.06.2017 / 20:52

1 answer

3

You can use sql.Date to generate util.Date from LocalDate :

java.util.Date date = java.sql.Date.valueOf(localDate);

And to do the reverse operation we use the toLocalDate method of class java.sql.Date

LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();

Translated by: en.stackoverflow

EDIT:

To generate a LocalDate from a String

DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MM-yyyy");
LocalDate seuLocalDate = dtf.parseLocalDate("25-06-2017");

//sua implementação
listaLivros.add(new Livro(1,123456,"Harry Potter","J.K Rowling","HP", seuLocalDate));

To make a java.sql.Date from a String you can do as follows:

String string = "25-06-2017";
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Date date = format.parse(string);
System.out.println(date); 

If you are trying to save a sql.Date within your ArrayList from a String , use the parse method of the DateFormat class, you can do this:

public class LivroService {

    private List<Livro> listaLivros;
    SimpleDateFormat sdt = new SimpleDateFormat("dd-MM-yyyy");

    public LivroService() {
        listaLivros = new ArrayList<>();
        listaLivros.add(new Livro(1,123456,"Harry Potter","J.K Rowling","HP",sdt.parse("12-10-2015")));
    }

}
    
25.06.2017 / 21:40