如何在datetimepicker jquery中检查日期范围?

时间:2016-10-28 03:04:35

标签: javascript jquery datetime datetimepicker

我在https://github.com/xdan/datetimepicker使用了datetimepicker,它非常酷,我想在一周(7天)内查看此日期范围,我尝试

               if ($("#FromDate").val() + 7 > $("#ToDate").val()) {
                   alert("Please choose a week");
                }

示例某些情况:

Fromdate: 27/10/2016 Todate: 31/10/2016 : OK
Fromdate: 27/10/2016 Todate: 2/11/2016 : OK
Fromdate: 27/10/2016 Todate: 3/11/2016 : show alert

但似乎不起作用。

2 个答案:

答案 0 :(得分:1)

我已经更新了答案并且工作正常。点击此处jsFiddle

var fromDate = new Date($("#FromDate").val());
var sevenDate = new Date(fromDate.setDate(fromDate.getDate() + 7));
var toDate = new Date($("#ToDate").val());

if (sevenDate > toDate) {
    alert("Please choose a week");
}

答案 1 :(得分:0)

这样做的方法是使用new Date()将日期字符串转换为日期对象
但是如果您使用'dd/mm/yy'格式会出现一个问题,那么当您转换时它将无效 它进入new Date()只是重新排列它的格式inyo一个有效的格式我使用格式'yy-mm-dd'

HTML

Start: <input id="from" type="text" /><br />
End: <input id="to" type="text" /><br />
<input id="thesubmit" type="button" value="Submit" /> 

JAVASCRIPT

$(document).on('click', '#thesubmit', function() {
    var from = new $("#from").val().split('/');
  var to = new $("#to").val().split('/');
  from = new Date(from[2]+'-'+from[1]+'-'+from[0]);
  to = new Date(to[2]+'-'+to[1]+'-'+to[0]);

  if (new Date(from) == 'Invalid Date' || new Date(to) == 'Invalid Date') {
    return alert('Select a valid date');
  }

  var timeDiff = Math.abs(to.getTime() - from.getTime());
        var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
        if (diffDays >= 7) {
    alert('It is 1 week range');
  }
})

DEMO