I want to calculate the total days of leave that can be apply in weekday.

startDate & endDate value i take from their fields in format of (month/day/year)

I have found the uncaught type error in this line -> startDate.setHours(0,0,0,1);

What is this? Anyone can help?


function workingDaysBetweenDates() {

var startDate = fd.field('StartDate').value();
var endDate = fd.field('_EndDate').value()

// Validate input
if (endDate < startDate)
    return 'Invalid !';

// 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;

2 Answers 2


Most probably this error occurs since setHours() is a function of Date object, but in your case startDate and endDate variables are of String type:

var startDate = fd.field('StartDate').value();
var endDate = fd.field('_EndDate').value()


Create a Date objects:

var startDate = new Date(fd.field('StartDate').value());
var endDate = new Date(fd.field('_EndDate').value());

This error is telling you that the startDate variable is undefined, i.e. it's empty, there's nothing in it.

You should check that your method of getting the start date from the form is working. I.e. check fd.field('StartDate').value();

Are you using the SharePoint Forms Designer tool? Have you included the Forms Designer script file?

If you've taken this code from elsewhere you will need to get the start and end date in a different way. jQuery is an option in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.