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.
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.
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.