Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Possible days in a date range using Javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 391
    Comment on it

    Possible days in Date Range using Javascript


    Hi friends,
    In some cases we try to build a logic where for a case where we need to find all the possible days that are possible inside a date range for any use case like scheduling a meeting or reminders, something like that. So here I am writing a few lines of codes that returns the array of possible days in a date range. I have used moment js here, that makes it easier to work on dates.

        function getPossibleDays(start_date, end_date) {
            //passed startdate and end dates can be in any format that are acceptable by moment, like YYYY-MM-DD
            var startDate = moment(start_date); //moment object of startDate
            var endDate = moment(end_date); //moment object of endDate
            var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
            if (endDate < startDate) {
                console.error("End date must be greater than or equal to start date.");
            } else {
                if (endDate.diff(startDate, 'days') >= 7) {
                // Return all days array
                return days;
              } else {
                var possibleDays = [];
                var iDate = startDate;
                while (iDate <= endDate) {
                  //Pusing the day into array
                  possibleDays.push(days[iDate.day()]);
                  //Incrementing date
                  iDate = iDate.add(1, 'days');
                }
                return possibleDays;
              }
            }
        }
    

    Now if you want the code to run. Here is the fiddle link for this. https://jsfiddle.net/raghvendra1501/an1bmo2p/2/ Hope you liked reading this blog.

    For more like this Click here.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: