java – Converter String para Date

Question:

I'm new to java and I'm in doubt about converting from String to Date. I've spent hours searching the internet to see if I could find a solution and I came across very few solutions but when I was going to put these solutions to run, my application always generated an error!

 private boolean salvarPessoa(){
        pessoa.setNome(this.txtNome.getText());
        pessoa.setBairro(this.txtBairro.getText());
        pessoa.setEndereco(this.txtEndereco.getText());
        pessoa.setCidade(this.txtCidade.getText());
        pessoa.setUf(this.txtUF.getText());
        pessoa.setCPF(this.txtCPF.getText());
        pessoa.setTelefone(this.txtTelefone.getText());
        pessoa.setdNascimento(this.txtdNascimento.getText());// <- O erro esta aqui!

Answer:

Create a SimpleDateFormat object initializing the date format according to how your String is formatted, then just parse the String and throw it into a Date. See the code:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Teste {
    public static void main(String[] args) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        String data = "16/10/2015";
        try {
            Date date = formatter.parse(data);
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Result:

Fri Oct 16 00:00:00 BRT 2015

See thepatterns to pass to SimpleDateFormat's constructor.

Scroll to Top