Date range restriction with JavaScript

梦想的初衷 提交于 2019-12-07 11:38:35

问题


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.


回答1:


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;

    }


来源:https://stackoverflow.com/questions/5755327/date-range-restriction-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!