Calculate difference between to dates / business days
Hello guys,
I have found solution on the forum but I have problem because it returns me 1 day as default result. (Probably because of timezone)
Anyone knows how to solve it?
var startDate = @DateStart
var endDate = @DateEnd
function workingDaysBetweenDates(startDate, endDate) {
// Validate input
if (endDate < startDate)
return 0;
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0,0,0,1); // Start just after midnight
endDate.setHours(23,59,59,999); // End just before midnight
var diff = endDate  startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
var days = days  (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay  endDay > 1)
days = days  2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
days = days  1
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
days = days  1
return days;
}
workingDaysBetweenDates( new Date(startDate) , new Date(endDate))

This is an old thread, but should this code still work?
I'm having issues counting the number of business days between two dates. I tried the same code but it says 'the results is not a valid number'.
@todaysDate is a calculation that update at 12:15am every day, is it possible that that's the issue?
var startDate = @Todays Date
var endDate = @Current Auction Datefunction workingDaysBetweenDates(startDate, endDate) {
// Validate input
if (endDate < startDate)
return 0;// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0,0,0,1); // Start just after midnight
endDate.setHours(23,59,59,999); // End just before midnight
var diff = endDate  startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
var days = days  (weeks * 2);// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();// Remove weekend not previously removed.
if (startDay  endDay > 1)
days = days  2;// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
days = days  1// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
days = days  1return days;
}startDate == null  endDate == null ? "" : workingDaysBetweenDates( new Date(startDate) , new Date(endDate))
Please sign in to leave a comment.
Comments
8 comments