再会 。我只是想问一下在给定日期添加天数。我有一个 jtexfield (txtStart) 和另一个 jtexfield(txtExpiry)。我需要在 txtExpiry 中显示自 txtStart 中的日期起 102 天后的日期。我正在使用 KEYRELEASED 事件。我在txtStart中输入后,txtExpiry中会出现额外102天的日期。
这是我的代码,但它仍然是错误的。
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.
}
我的代码仍然不会在 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);
}
}