How to calculate the number of days between two dates except java weekend

Hi, I am trying to have this code have days of work (including weekends), so how can I exclude 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; } 
+4
source share
2 answers

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 
+11
source

You can use the following code:

 public class DateUtils{ private static final DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MMM-dd"); public static void main(String[] args){ try { Date beg = ((args.length > 0) ? DEFAULT_DATE_FORMAT.parse(args[0]) : new Date()); Date end = ((args.length > 1) ? DEFAULT_DATE_FORMAT.parse(args[1]) : new Date()); System.out.println("beg: " + DEFAULT_DATE_FORMAT.format(beg)); System.out.println("end: " + DEFAULT_DATE_FORMAT.format(end)); System.out.println("# days between: " + interval(beg, end, new IncludeAllDateRule(), Calendar.DATE)); System.out.println("# weekdays between: " + interval(beg, end, new ExcludeWeekendDateRule(), Calendar.DATE)); System.out.println("# hours between: " + interval(beg, end, new IncludeAllDateRule(), Calendar.HOUR)); System.out.println("# minutes between: " + interval(beg, end, new IncludeAllDateRule(), Calendar.MINUTE) ); } catch (ParseException e) { e.printStackTrace(); } } public static int interval(Date beg, Date end, DateRule dateRule, int intervalType) { Calendar calendar = Calendar.getInstance(); calendar.setTime(beg); int count = 0; Date now = calendar.getTime(); while (now.before(end)) { calendar.add(intervalType, 1); now = calendar.getTime(); if (dateRule.include(now)) { ++count; } } return count; } } interface DateRule{ boolean include(Date d); } class ExcludeWeekendDateRule implements DateRule { public boolean include(Date d) { boolean include = true; Calendar calendar = Calendar.getInstance(); calendar.setTime(d); int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); if ((dayOfWeek == Calendar.SATURDAY) || (dayOfWeek == Calendar.SUNDAY)) include = false; return include; } } class IncludeAllDateRule implements DateRule { public boolean include(Date d) { return true; } } 
0
source

Source: https://habr.com/ru/post/1498169/


All Articles