比较使用datepicker的两个日期

时间:2015-10-21 10:38:23

标签: javascript jquery datepicker

我有一个有两个日期字段的表单。我试图从两个输入中选择日期并将它们与JQuery进行比较。我遇到的问题是它返回NaN

我想可能是因为日期上的typeof会返回字符串。

$('#id_date_completed').change(function() {
    date_received = $("#id_date_received").val(); 
    date_completed = $("#id_date_completed").val(); 

    var diff = date_completed - date_received;
    var days = diff / 1000 / 60 / 60 / 24;

    console.log(days);
}

修改

我的问题与Get difference between 2 dates in javascript?不同,因为我正在使用bootstrap-datepicker库。 Arun P Johny的回答很完美

1 个答案:

答案 0 :(得分:5)

问题是.val()将返回一个字符串,因此date_receiveddate_completed都是字符串值,因此减去它们将返回NaN

相反,您可以使用getDate()

bootstrap-datepicker方法



$("#id_date_received, #id_date_completed").datepicker();

$('button').click(function() {
  var date_received = $("#id_date_received").datepicker('getDate');
  var date_completed = $("#id_date_completed").datepicker('getDate');

  var diff = date_completed - date_received;
  var days = diff / 1000 / 60 / 60 / 24;
  $('span').text(days)
})

<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"></script>

<input id="id_date_received" />
<input id="id_date_completed" />
<button>Test</button>
<span></span>
&#13;
&#13;
&#13;