how to add number of days to the date given in a jtextfield with string data type

zairahCS picture zairahCS · Mar 13, 2012 · Viewed 19.2k times · Source

Good Day . I just wanna ask about adding days in a given date. I have a jtexfield (txtStart) and another jtexfield(txtExpiry). I need to display in txtExpiry the date after 102 days from the date in txtStart. I am using KEYRELEASED event. after i input in txtStart, the date with additional 102 days shall appear in txtExpiry.

here's my code but it's still erroneous.

private void txtStartKeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
    // set calendar to 1 Jan 2007
    int a = Integer.parseInt(txtStart.getText());     
    Calendar calendar = new GregorianCalendar(a,a,a);

     calendar.add(Calendar.DAY_OF_MONTH,102);
     PrintCalendar(calendar);
  }

   private void PrintCalendar(Calendar calendar){
        // define output format and print
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");         
        String date = sdf.format(calendar.getTime());
        long add = Date.parse(date);
        txtExpiry.setText(add);  -----> this part here also has an error.
     }

my code still won't generate the date in txtExpiry. Thanks in advance

Here's the right code after receiving help:

 private void txtStartKeyReleased(java.awt.event.KeyEvent evt) {
       try {    

        Date date1;
        date1 = new SimpleDateFormat("yyyy-MM-dd").parse(txtStart.getText());
        System.out.println(date1);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");     
        Calendar cal  = Calendar.getInstance();
                      cal.setTime(date1);
                        cal.add(Calendar.DATE, 102);
                        String expDateString = sdf.format(cal.getTime());
                        txtExpiry.setText(expDateString);
     }catch (ParseException ex) {
      Logger.getLogger(ClientInfo.class.getName()).log(Level.SEVERE, null, ex);
     } 
}  

Answer

jmj picture jmj · Mar 13, 2012

Use

yyyy-MM-dd

Note: Capital MM

See : SimpleDateFormat

Now, once you have the date instance you could use Calendar to do the days arithmetic

Calendar cal = Calendar.getInstance();
cal.setTime(parsedDate);
cal.add(Calendar.DATE, 102);
String expDateString = dateFormatter.format(cal.getTime());