Created
July 14, 2023 09:00
-
-
Save danylkaaa/03a20a68362a0df6ada773ce6c3f6764 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
const MS_IN_WEEK = 1000 * 3600 * 24 * 7; | |
const MS_IN_DAY = 1000 * 3600 * 24; | |
function setDay(date, day) { | |
return new Date(date.getTime() + (day - date.getDay() * MS_IN_DAY)); | |
} | |
function getWeekDayOccurrences(dateRange, dayId) { | |
const [dayStart, dayEnd] = dateRange; | |
const startDayId = dayStart.getDay(); | |
const endDayId = dayEnd.getDay(); | |
const firstDayAfterStartWeek = new Date( | |
setDay(dayStart, 0).getTime() + MS_IN_DAY * 7 | |
); | |
const lastDayBeforeEndWeek = new Date( | |
setDay(dayEnd, 0).getTime() | |
); | |
const fullWeeks = | |
Math.ceil((lastDayBeforeEndWeek - firstDayAfterStartWeek) / MS_IN_WEEK); | |
let occurrences = fullWeeks>0?fullWeeks:0; | |
if (fullWeeks>=0) { | |
if (startDayId <= dayId) { | |
occurrences += 1; | |
} | |
if (endDayId >= dayId) { | |
occurrences += 1; | |
} | |
}else{ | |
if (startDayId <= dayId && endDayId >= dayId) { | |
occurrences += 1; | |
} | |
} | |
return occurrences; | |
} | |
console.log(); | |
console.log(); | |
console.log(); | |
console.log(); | |
console.log( | |
getWeekDayOccurrences([new Date("2023/01/28"), new Date("2023/08/04")], 2), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment