如何计算除周末java之外的两个日期之间的天数

如何计算除周末java之外的两个日期之间的天数

问题描述:

我试试这段代码有几天的工作(包括周末),那么我怎样才能在两个日期之间排除周末?

Hi, i try this code to have days of works (including weekends) , so how can i exlude weekends between two dates ?

public long getDifferenceDays(Date d1, Date d2) {
  long diff = d2.getTime() - d1.getTime();
  long diffDays = diff / (24 * 60 * 60 * 1000);
  return diffDays;
}


这对你有用

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date date1 = df.parse("10/08/2013");
    Date date2 = df.parse("21/08/2013");
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal1.setTime(date1);
    cal2.setTime(date2);

    int numberOfDays = 0;
    while (cal1.before(cal2)) {
        if ((Calendar.SATURDAY != cal1.get(Calendar.DAY_OF_WEEK))
           &&(Calendar.SUNDAY != cal1.get(Calendar.DAY_OF_WEEK))) {
            numberOfDays++;
        }
        cal1.add(Calendar.DATE,1);
    }
    System.out.println(numberOfDays);

实时演示

Out put

7