How to save a localdate to a mysql table?

Asked

Viewed 942 times

2

I have a table book that has a column like "Date" and in my java code I have a field like "localdate". I need to save the data from the "Localdate" field in the table but I’m 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")));
    }

}
  • Related question: https://answall.com/q/177129/132

  • @Victorstafusa thanks for responding but I even know how to make the conversion, what I do not know how to save in the comic.

1 answer

4


You can do it using the sql.Date generate a util.Date from a LocalDate:

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

And to do the reverse operation the method is used toLocalDate class java.sql.Date

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

Translated from: 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 it this way:

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

If you’re trying to save one sql.Date within your ArrayList from a String, use the method parse class DateFormat, can do as follows:

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")));
    }

}
  • I tried to do according to your suggestion but it didn’t work out. java.util.Date date = java.sql.Date.valueOf("12-10-2015"); and then I did this listaLivros.add(new Livro(1,123456,"Harry Potter","J.K Rowling","HP",date)); after that he asks to create a builder that makes no sense

  • I made an edit in my reply adding how to catch a sql.Date from a String, that at first is what you’re trying to do

  • 1

    Thanks, it worked out!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.