Convert String to Date

Asked

Viewed 8,022 times

3

I’m a beginner in java and I’m having doubts about converting String to Date. I already 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 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!
  • 4

    I think there’s a hundreds questions like this.

  • What is the format of the date string? And as @bigown said, what else is on Sopt are questions about date formatting, like this, this, etc. Just read the documentation and find out the format you need.

  • Format: day, month and year. I have read more I know almost nothing of the English vocabulary and I can not even read in English.

2 answers

8


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

Upshot:

Fri Oct 16 00:00:00 BRT 2015

See the Patterns to pass to the Simpledateformat constructor.

1

You can pass the variable of type String as parameter to 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 in the format YYYY :

@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
}

Browser other questions tagged

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