如何在带有字符串数据类型的jtextfield中给出的日期添加天数

zai*_*hCS 3 java datetime gregorian-calendar simpledateformat

美好的一天 .我只是想问一下在给定日期添加天数.我有一个jtexfield(txtStart)和另一个jtexfield(txtExpiry).我需要在txtExpiry中显示自txtStart日期起102天后的日期.我正在使用KEYRELEASED事件.在输入txtStart之后,额外102天的日期将出现在txtExpiry中.

这是我的代码,但它仍然是错误的.

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.
     }
Run Code Online (Sandbox Code Playgroud)

我的代码仍然不会在txtExpiry中生成日期.提前致谢

收到帮助后,这是正确的代码:

 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);
     } 
}  
Run Code Online (Sandbox Code Playgroud)

Jig*_*shi 7

使用

yyyy-MM-dd
Run Code Online (Sandbox Code Playgroud)

注:资本MM

见: SimpleDateFormat

现在,一旦你有了日期实例,你可以Calendar用来做日算术

Calendar cal = Calendar.getInstance();
cal.setTime(parsedDate);
cal.add(Calendar.DATE, 102);
String expDateString = dateFormatter.format(cal.getTime());
Run Code Online (Sandbox Code Playgroud)

  • 我假设你在jTextField中有String形式的日期,例如:``1987-12-24`,现在你可以使用`SimpleDateFormat`将字符串变为'Date`和`Date`变为`Calendar` (2认同)