Search code examples
javascriptangularjsmomentjsangular-moment

Javascript - Calculate number of days between two weekdays


I looking for a function that calculate the day difference between two weekdays. Like, for eg.

Monday - Friday = 4
Sunday - Saturday = 6

Thank you!


Solution

  • Just create an object with the weekdays' values.

    Let's call it weekdays. The purpose of this object is to keep the value for every day from a week.

    Then just create an algorithm in order to find out the difference.

    var weekdays = {
           "Monday" : 1,
           "Tuesday" : 2,
           "Wednesday" : 3,
           "Thursday" : 4,
           "Friday" : 5,
           "Saturday" : 6,
           "Sunday" : 7
    }
    
    getBetweenWeekDays = function(day1, day2){
       if(weekdays[day1] <= weekdays[day2])
         return weekdays[day2] - weekdays[day1];
       return 7 - weekdays[day1] + weekdays[day2];
    };
    console.log('Monday - Friday = ' + getBetweenWeekDays('Monday','Friday')); 
    console.log('Sunday - Saturday = ' + getBetweenWeekDays('Sunday','Saturday'));
    console.log('Wednesday - Tuesday = ' + getBetweenWeekDays('Wednesday','Tuesday'));
    console.log('Tuesday - Wednesday = ' + getBetweenWeekDays('Tuesday','Wednesday'));