Search code examples
javascriptdate-range

Date range restriction with JavaScript


There are two input fields of type text to write a start date and end date in format mm/dd/yyy. I need a JavaScript function to check that the date range interval between those entered dates does not exceed 14 days. And the maximum date should be the current date. Is there a plugin or a fast solution for this? I tried to use the jQuery UI datepicker which would work fine, but I have a custom GetElementByClassName function which conflicts with jQuery.

Thank you.


Solution

  • The following snippets should give you some ideas.

    <script>
        var date1 = '01/14/2011';
        var date2 = '01/25/2011';
    
        // calculate the number of days between date1 and date2
        var daysBetween = new Date(date2).getTime() - new Date(date1).getTime();
        alert('days between = ' + daysBetween / 86400000);
    
        // check date3 against current date
        var now = new Date();
        var date3 = new Date('04/20/2011');
        if (date3 < now)
          alert('date3 is less than current date');
    
    </script>
    

    So to combine into a function, you could do something like this:

    <script>
        function checkDates(date1, date2) {
            // calculate the number of days between date1 and date2
            var daysBetween = (new Date(date2).getTime() - new Date(date1).getTime()) / 86400000;
    
            if (daysBetween > 14)
              return false;
    
            var now = new Date();
            if (date2 < now)
              return false;
    
            return true;
    
        }