计算两个日期之间的差异

时间:2013-06-29 04:06:40

标签: javascript calendar

我试图计算两个日期之间的差异,我编写了java脚本函数,它工作正常,但问题是它处理的是几个月的日子,反之亦然。

例如: 如果第一个日期是2013年2月7日,第二个日期是2013年3月7日 给我结果30天而不是1天。

这是我的代码:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery- ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<script>
$(function() {
$( "#from" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
}});
$( "#to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
</script>
<form method="post" action="" name="date">

<label for="from"> Start Date : </label>
<input type="text" id="from" name="start" />
<br/>
<label for="to">   End Date : </label>
<input type="text"  id="to"  name="end"/>
<br/>
<input type="submit" name="Submit" value="reserve"    onclick="setDifference(this.form);"/></p>

<input type="hidden" name="result"  />
</form>


<script type="text/javascript">

function setDifference(frm) {
var dtElem1 = frm.elements['start'];
var dtElem2 = frm.elements['end'];
var resultElem = frm.elements['result'];

if(!dtElem1 || !dtElem2 || !resultElem) {
return;
}

var x = dtElem1.value;
var y = dtElem2.value;
var arr1 = x.split('/');
var arr2 = y.split('/');


var dt1 = new Date();
dt1.setFullYear(arr1[2], arr1[1], arr1[0]);
var dt2 = new Date();
dt2.setFullYear(arr2[2], arr2[1], arr2[0]);

resultElem.value = (dt2.getTime() - dt1.getTime()) / (60 * 60 * 24 * 1000);
}
</script>

<?php

$from= $_POST['start'];
$to= $_POST['end'];
$result = $_POST['result']; 
?>

Check In Date : <?php echo $from; ?></label><br />
Check Out Date : <?php echo $to; ?></label><br />
Number Of days: <?php echo $result; ?></label><br />
<BR/>

1 个答案:

答案 0 :(得分:0)

mm / dd / yyyy not dd / mm / yyyy

var dt1 = new Date();
dt1.setFullYear(arr1[1], arr1[2], arr1[0]);
var dt2 = new Date();
dt2.setFullYear(arr2[1], arr2[2], arr2[0]);

resultElem.value = (dt2.getTime() - dt1.getTime()) / (60 * 60 * 24 * 1000);