Convert string to calendar [closed]

2

I need to do a String to calendar conversion, so I have to set the value in a variable (which is in calendar type) in a class and then insert the data into a database!

System.out.println("Digite a Data de Aniversario do Funcionario");
 String data = scan1.nextLine();
 SimpleDateFormat form = new SimpleDateFormat("yyyy/MM/dd");
 Date data1 =(Date)form.parse(data);
 Calendar cal = Calendar.getInstance();
 cal.setTime(data1);
 f.setDataAniver(cal.setTime(data1));
    
asked by anonymous 06.03.2016 / 00:07

1 answer

1

Assuming the column where you want to write this information is of type Date and you are using JDBC, you can convert the format Calendar to java.sql.Date direct in setDate() of your PrepareStatement , see example :

    //...

    pstm.setDate(new java.sql.Date(f.getDataAniver().getTimeInMillis()));

    //...

There is no need to format as yyyy/MM/dd , even if the date value enters Brazilian format or another custom format in Calendar , when converting using java.sql.Date , the default formatting ( ISO 8601 ) of the type will be applied, see the example below:

    String strDate = "01/07/1990";
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Calendar c = Calendar.getInstance();     
    c.setTime(sdf.parse(strDate));
    //aqui está o "pulo do gato"
    System.out.println(new java.sql.Date(c.getTimeInMillis()));

What it displays:

  

1990-07-01

See an example above working on IDEONE .

    
06.03.2016 / 02:53