Calculate the difference between two dates, ignoring weekends


The attached Java file contains three methods: the div() method provides integer division with rounding towards negative infinity, which Java does not provide by itself (the normal division and modulus operations round towards zero). Use of this function makes the other methods usable with dates before 1970 because it will handle negative numbers correctly.

The wdnum() method returns the number of weekdays (excluding weekends) that have passed since Monday, 29 December 1969. It works by calculating the number of days since 1 January, 1970 (getTime() divided by the number of milliseconds in a day), adding 3 and returning the number of week days in full weeks and possibly a partial week that have passed since then.

The diff() method shows one possible use of wdnum(): it calculates the number of weekdays that have passed between two given dates, excluding weekends.

An example use of the diff() function would be to calculate the number of working days in a month. This could be done as follows:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(year, month, 1);
Date d1 = cal.getTime();
cal.set(year, month + 1, 1);
Date d2 = cal.getTime();
System.out.println("Month " + month + ", " + year + " has " + diff(d1, d2) + " working days");

Note that the Calendar has to be set to the UTC time zone because the Date objects passed to diff() are expected to be relative to UTC.

You might also like...




Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” - Donald Knuth