Jquery日期验证 - 截止日期> =开始日期

时间:2017-01-11 04:10:06

标签: javascript jquery

代码:

function randomDate(start, end) {
        return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
    }

    function DateAndTimeFormate(date) {
        var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
      "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"
        ];
      var date = new Date(date);
      return date.getDate() + '-' + monthNames[(date.getMonth() + 1)] + '-' +  date.getFullYear();
    }

    var datewithformate = DateAndTimeFormate(randomDate(new Date(0000, 0, 0), new Date()));
    $("#startdate").val(datewithformate)

    var datewithformate1 = DateAndTimeFormate(randomDate(new Date(0000, 0, 0), new Date()));

    $("#enddate").val(datewithformate1)

while(Date.parse(datewithformate1) < Date.parse(datewithformate))
{


    $("#enddate").val(datewithformate1)
}

我希望我的结束日期始终为&gt; =(大于等于)开始日期。我尝试了解析方法。代码运行时,它没有给我所需的输出。我错过了什么?

1 个答案:

答案 0 :(得分:0)

Enddate不能总是大于等于开始日期。因为你正在调用随机函数。每次随机化日期。 但你可以追踪它何时可以更大或相等,何时不能。

    function randomDate(start, end) {
        return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
    }

    function DateAndTimeFormate(date) {
        var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
      "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"
        ];
      var date = new Date(date);
      return date.getDate() + '-' + monthNames[(date.getMonth() + 1)] + '-' +  date.getFullYear();
    }

    var datewithformate = DateAndTimeFormate(randomDate(new Date(0000, 0, 0), new Date()));
    $("#startdate").val(datewithformate)

    var datewithformate1 = DateAndTimeFormate(randomDate(new Date(0000, 0, 0), new Date()));

    $("#enddate").val(datewithformate1)
    DateRecursion();

// if end date is greater then equal to start date...
function DateRecursion() {
      if(Date.parse(datewithformate1) >= Date.parse(datewithformate))
      {
          alert("end date is greater then equal to start date");
      }
      datewithformate1 = DateAndTimeFormate(randomDate(new Date(0000, 0, 0), new Date()));
      datewithformate = DateAndTimeFormate(randomDate(new Date(0000, 0, 0), new Date()));
      DateRecursion();
}

我想你的html喜欢

<label>Start date</label><br><input type="text" id="startdate" />
<label>End date</label><br><input type="text" id="enddate" />