Last active
November 1, 2022 07:49
-
-
Save Tinomuchenje/32385bb0dd007754b903da2cae790141 to your computer and use it in GitHub Desktop.
Calculate business hours excluding weekends and holidays formatted to nearest 30 mins. Typescript || Javascript
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
let startDate = new Date('2022/12/25 8:00'); | |
let endDate = new Date('2022/12/27 9:30'); | |
function calculateBusinessDays(startDate, endDate) { | |
var minutesWorked = 0; | |
var holidays = ['2022/12/25', '2022/12/26'] | |
var workHoursStart = 8; | |
var workHoursEnd = 17; | |
let roundToNearest30 = (dateInput) => { | |
const minutes = 30; | |
const ms = 1000 * 60 * minutes; | |
return new Date(Math.ceil(dateInput.getTime() / ms) * ms); | |
} | |
startDate = roundToNearest30(startDate); | |
endDate = roundToNearest30(endDate); | |
for (var currentDate = new Date(startDate); currentDate <= endDate; currentDate.setTime(currentDate.getTime() + 1000 * 60)) { | |
var currentDateString = `${currentDate.getFullYear()}/${currentDate.getMonth() + 1}/${currentDate.getDate()}`; | |
if (currentDate.getDay() != 0 && currentDate.getDay() != 6 | |
&& currentDate.getHours() >= workHoursStart && currentDate.getHours() < workHoursEnd | |
&& holidays.indexOf(currentDateString) == -1 | |
) { | |
minutesWorked++; | |
} | |
} | |
return (minutesWorked / 60).toFixed(1); | |
} | |
console.log(calculateBusinessDays(startDate, endDate)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment