我需要计算除假期(星期六和星期日)之外的天数。例如,我的开始日期为07/02/2018
,结束日期为15/02/2018
(格式为dd/MM/yyyy
)。我需要计算它们之间的工作日数。有人可以帮帮我吗?这是我的代码:
SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
//Date date12 = dateformat3.parse("17/07/1989");
String date1 = "11/07/2018";
String date2 = "20/07/2018";
// Date date2 = dateformat3.parse("15/10/2007");
Calendar startdate = Calendar.getInstance();
startdate.setTime(dateformat3.parse(date1));
Calendar enddate = Calendar.getInstance();
enddate.setTime(dateformat3.parse(date2));
while (!startdate.after(enddate)) {
int day = startdate.get(Calendar.DAY_OF_WEEK);
if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
workingDays++;
}
}
我已尝试使用此代码,但未显示任何结果。
答案 0 :(得分:1)
你很接近,只需要在循环中增加开始日期。
public static void main(String[] args) throws Exception {
System.out.println(countDays("07/02/2018", "15/02/2018"));
}
public static int countDays(String startDate, String endDate) throws Exception {
int workingDays = 0;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar startdate = Calendar.getInstance();
startdate.setTime(sdf.parse(startDate));
Calendar enddate = Calendar.getInstance();
enddate.setTime(sdf.parse(endDate));
while (!startdate.after(enddate)) {
int day = startdate.get(Calendar.DAY_OF_WEEK);
System.out.println(day);
if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
workingDays++;
}
// increment start date, otherwise while will give infinite loop
startdate.add(Calendar.DATE, 1);
}
return workingDays;
}
正如您所看到的,与我提供的代码(除了删除硬编码值之外)的唯一区别是startdate.add(Calendar.DATE, 1);
答案 1 :(得分:0)
我认为你的状况有问题。 试试这个
while (ChronoUnit.DAYS.between(startdate.toInstant(), enddate.toInstant()) > 0) {
startdate.add(Calendar.DAY_OF_MONTH, 1);
if (startdate.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startdate.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
workingDays++;
}
}
答案 2 :(得分:0)
如果您使用的是Java 8,则可以使用:
//Here I change the format of date to make it parsable
String date1 = "2018-07-11";
String date2 = "2018-07-20";
//Parse the date to LocalDate
LocalDate start = LocalDate.parse(date1);
LocalDate end = LocalDate.parse(date2);
//iterate over the list of dates between start and end date,
//then filter only those who are not equal SATURDAY or SUNDAY, then count the result
long result = Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, end))
.filter(date -> date.getDayOfWeek() != DayOfWeek.SATURDAY
&& date.getDayOfWeek() != DayOfWeek.SUNDAY
).count();
在您的情况下,它将返回7天