Question

I have these date variables

minVal = new Date(parseInt(dateArr[2]), parseInt(dateArr[0]) - 1, parseInt(dateArr[1]), 00, 00, 00);
maxVal = new Date(parseInt(dateArrTo[2]), parseInt(dateArrTo[0]) - 1, parseInt(dateArrTo[1]), 23, 59, 59);

I use them to draw charts.

I need to differentiate between two things:

  1. During 30 days charts.
  2. After 30 days charts.

Thus, I need to know the different between these dates in days

I tried to do this:

if ((maxVal.getMonth() - minVal.getMonth()) == 0)

It works with some values and doesn't work with some values. For example, if the minimum date is 29 January 2014 and the maximum date is 01 February 2014 it doesn't work. I know that because I am calculating the months.

But I don't know how to calculate the days

I know that getDate() function retrieves the days number but I really couldn't know how to use it.

your help is appreciated

Was it helpful?

Solution

Try this

function workingDaysBetweenDates(startDate, endDate, getWorkingDays) {

    startDate = new Date(startDate);
    endDate = new Date(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);

    if(getWorkingDays){
        // Subtract two weekend days for every week in between
        var weeks = Math.floor(days / 7);
        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(start_date, end_date, false);

Here is the working Fiddle: http://jsfiddle.net/kailashyadav/72b27/

Date format needs be one of these: 04/24/2014 or 2014-04-24

The third parameter is whether you want to get business or calendar days

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top