Created
December 2, 2015 22:31
-
-
Save batterseapower/586a925a34ba2a85f51a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DenseDates { | |
private DenseDates() {} | |
// 0 == Monday, 6 == Sunday | |
private static int epochDayToDayOfWeek0Based(long epochDay) { | |
return (int)Math.floorMod(epochDay + 3, 7); | |
} | |
public static int daysBetween(long fromEpochDay, long toEpochDay) { | |
// http://stackoverflow.com/questions/1617049/calculate-the-number-of-business-days-between-two-dates | |
final int fromDOW = epochDayToDayOfWeek0Based(fromEpochDay); | |
final int toDOW = epochDayToDayOfWeek0Based(toEpochDay); | |
long calcBusinessDays = ((toEpochDay - fromEpochDay) * 5 + (toDOW - fromDOW) * 2) / 7; | |
if (toDOW == 6) calcBusinessDays -= 1; | |
if (fromDOW == 6) calcBusinessDays += 1; | |
return (int)calcBusinessDays; | |
} | |
public static long addDays(long epochDay, int n) { | |
// https://alecpojidaev.wordpress.com/2009/10/29/work-days-calculation-with-c/ | |
// NB: in .NET, Sunday == 0, but in our code Monday == 0 | |
final int dow = (epochDayToDayOfWeek0Based(epochDay) + 1) % 7; | |
final int wds = n + (dow == 0 ? 1 : dow); // Adjusted number of working days to add, given that we now start from the immediately preceding Sunday | |
final int wends = n < 0 ? ((wds - 5) / 5) * 2 | |
: (wds / 5) * 2 - (wds % 5 == 0 ? 2 : 0); | |
return epochDay - dow + // Find the immediately preceding Sunday | |
wds + // Add computed working days | |
wends; // Add weekends that occur within each complete working week | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment