7

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;
}
Dominic Weiser
  • 1,446
  • 1
  • 20
  • 32
HamzaNTFS
  • 103
  • 1
  • 1
  • 7

1 Answers1

13

This will work for you

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);

Live Demo

Out put

7
cnmuc
  • 6,025
  • 2
  • 24
  • 29
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • 1
    Easy to understand solution. Add 1 to final `numberOfDays` (after the while loop) to include end day. Thanks for this! – k_rollo Jul 15 '17 at 11:59