Convert String to Date

2

I'm new to java and am having a question about converting String to Date. I've spent hours researching the internet to see if I could find any solution and I came across very few solutions but when I was going to put these solutions to run, my application always generated 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!
    
asked by anonymous 16.10.2015 / 16:54

2 answers

5

Create a SimpleDateFormat object by initializing the date format according to how your String is formatted, then just parse the String and play in 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 the patterns to switch to the SimpleDateFormat constructor.

    
16.10.2015 / 16:59
1

You can pass the String variable as a parameter to the formatter.parse and get the expected result as in the example:

@Test
public void testConversaoDataFormatoYY() throws ParseException {
    String exemplo = "10/16/15";
    DateFormat formatter = new SimpleDateFormat("MM/dd/yy");  
    Date date = (Date)formatter.parse(exemplo); 
    //System.out.println(date);
    //Fri Oct 16 00:00:00 BRT 2015
}

or with the YYYY format:

@Test
public void testConversaoDataFormatoYYYY() throws ParseException {
    String exemplo = "10/16/2015";
    DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    Date date = (Date)formatter.parse(exemplo); 
    //System.out.println(date);
    //Fri Oct 16 00:00:00 BRT 2015
}
    
16.10.2015 / 17:05