這應該添加weekdays
工作日(週末被忽略)上的日期。如果您通過0
獲得weekdays
,它將獲得下一個工作日。那麼,Saturday + 1 weekday = Tuesday
。
private static Date addWeekdaysToDate(Date date, int weekdays) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int originalDayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int numWeeks = weekdays/5;
int remainderDays = weekdays % 5;
cal.add(Calendar.DAY_OF_MONTH, numWeeks * 7 + remainderDays);
int adjustmentDays = 0;
if (originalDayOfWeek == Calendar.SUNDAY) {
adjustmentDays = 1;
} else if (originalDayOfWeek + remainderDays > Calendar.FRIDAY) {
adjustmentDays = 2;
}
cal.add(Calendar.DAY_OF_MONTH, adjustmentDays);
return cal.getTime();
}
編輯:
在你的代碼,只需替換爲以下:
private static Date addWeekdaysToDate(Date date, int weekdays) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int originalDayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int numWeeks = weekdays/5;
int remainderDays = weekdays % 5;
cal.add(Calendar.DAY_OF_MONTH, numWeeks * 7 + remainderDays);
int adjustmentDays = 0;
if (originalDayOfWeek == Calendar.SUNDAY) {
adjustmentDays = 1;
} else if (originalDayOfWeek + remainderDays > Calendar.FRIDAY) {
adjustmentDays = 2;
}
cal.add(Calendar.DAY_OF_MONTH, adjustmentDays);
return cal.getTime();
}
private static SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
private void txtStartKeyReleased(java.awt.event.KeyEvent evt) {
try {
txtExpiry.setText(
inputDateFormat.format(
addWeekdaysToDate(inputDateFormat.parse(txtStart.getText()), 102)
)
);
} catch (ParseException ex) {
Logger.getLogger(ClientInfo.class.getName()).log(Level.SEVERE, null, ex);
}
}
,我沒有得到你的問題。你想包括週末嗎?不包括週末的 – raddykrish 2012-03-13 20:33:23
。它應該是102天到期,但是週末不應該計算在內 – zairahCS 2012-03-13 20:35:42