Created
April 3, 2020 18:11
-
-
Save bwindels/b8bd0f58cd2788785ceb86a6fd61ebee to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function datePart(datetime) { | |
return new Date(datetime.getFullYear(), datetime.getMonth(), datetime.getDate()); | |
} | |
function daysFromNextWeekday(weekday, weekdayRef) { | |
return ((weekdayRef - weekday) + 7) % 7; | |
} | |
function amountOfWeekdayInRange(startWeekday, weekdayRef, dayCount) { | |
const daysToFirstOccurence = daysFromNextWeekday(startWeekday, weekdayRef); | |
if (daysToFirstOccurence <= dayCount) { | |
const daysFromFirstOccurence = dayCount - daysToFirstOccurence; | |
return 1 + Math.floor(daysFromFirstOccurence / 7); | |
} else { | |
return 0; | |
} | |
} | |
function weekDaysBetween(datetime1, datetime2) { | |
if (!datetime1 || !datetime2) { | |
return 0; | |
} | |
const date1 = datePart(datetime1); | |
const date2 = datePart(datetime2); | |
const daysBetween = Math.round((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)); | |
// convert to monday = 0 (from sunday = 0) | |
const startWeekday = (date1.getDay() + 7 - 1) % 7; | |
let amountOfSaturdays = amountOfWeekdayInRange(startWeekday, 5, daysBetween); | |
let amountOfSundays = amountOfWeekdayInRange(startWeekday, 6, daysBetween); | |
return daysBetween - amountOfSaturdays - amountOfSundays; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment