Add days to a jDateChooser

1

I would like to add 45 days to my date2, from the date1 Example:

data2 = data1 + 45

 public void adiciona(Usuario usuario){


    String sql = "INSERT INTO usuario(nome,endereco,cpf,email,telefone,data1,data2) VALUES(?,?,?,?,?,?,?)";
    try {

       PreparedStatement stmt = connection.prepareStatement(sql);
       java.sql.Date data1 = new java.sql.Date(usuario.getData1().getTime()); 


       stmt.setString(1, usuario.getNome());
       stmt.setString(2, usuario.getEndereco());
       stmt.setString(3, usuario.getCpf());           
       stmt.setString(4, usuario.getEmail());
       stmt.setString(5, usuario.getTelefone());
       stmt.setDate(6, data1);
       stmt.setDate(7, data2 );  //QUERO ADICIONAR A DATA2 NO BANCO COM 45 DIAS APÓS A DATA1, COMO FAZER?

       stmt.execute();
       stmt.close();

    } catch (SQLException u) {
        throw new RuntimeException(u);
    }
}

interface

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
// instanciando a classe Usuario do pacote modelo e criando seu objeto usuarios
Usuario usuarios = new Usuario();
usuarios.setNome(jTextField1.getText()); 
usuarios.setEndereco(jTextField2.getText());
usuarios.setCpf(jTextField3.getText());
usuarios.setEmail(jTextField4.getText());
usuarios.setTelefone(jTextField5.getText());
usuarios.setData1(jDateChooser1.getDate());
    
asked by anonymous 07.08.2014 / 16:44

2 answers

1

If you have to use the native libraries pre Java 8 you can do this:

Calendar c1 = Calendar.getInstance(); //pega data e hora atual
java.sql.Date data1 = new java.sql.Date(c1.getTimeInMillis()); //transforma p/ java.sql.Date
System.out.println(data1); //imprime para testar
c1.add(Calendar.DAY_OF_YEAR, 45); //soma 45 dias
data1.setTime(c1.getTimeInMillis()); //transforma para java.sql.Date
System.out.println(data1);//imprime para testar

Result:

  

2014-08-07
  2014-09-21

The above code is just a working example, for your case you will need to associate with the%% variable the value of your c1 variable like this:

c1.setTime(data1);

instead of picking up current date and time. At the same time, notice that where I created data1 in my example I did just the opposite way, I initialized it with the value of data1 . Both cases are possible.

    
07.08.2014 / 16:57
0

When I needed it I used this function and it worked very well:

   public Date somaDias(Date data, int dias) {
        Calendar cal = new GregorianCalendar();

        cal.setTime(data);

        cal.add(Calendar.DAY_OF_MONTH, dias);

        return cal.getTime();
    }
    
07.08.2014 / 17:19