我可以在我输入的任何日期添加102天,但现在问题是,它应该是102 周天(不包括周末)。我怎么能这样做?
这是我的代码,只需添加102天:
private void txtStartKeyReleased(java.awt.event.KeyEvent evt) {
try {
Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(txtStart.getText());
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);
}
}
答案 0 :(得分:0)
以下情况如何?
for (int i = 1; i <= 102; i++)
{
DateTime thisOne = DateTime.Parse("2012-03-13");
string thisDay = thisOne.ToString("dddd");
if (thisDay != "Saturday" && thisDay != "Sunday")
{
cal.add(Calendar.DATE, i);
}
}
编辑:已更新自定义日期
答案 1 :(得分:0)
我只是粘贴代码片,不包括周末。请根据您的目的使用此
int numberOfDays = 102;
int count = 1;
String expDateString = null;
Date temp = date1;
while(count != numberOfDays){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(temp);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK );
if(!(dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY)){
cal.add(Calendar.DATE, count);
count++;
}
temp = cal.getTime();
expDateString = sdf.format(cal.getTime());
}
答案 2 :(得分:0)
这应该将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);
}
}