0

我想计算 startdatetime 和 enddatetime 之间的差异

这是我的html代码:

StartDate:<input size="16" type="text" placeholder="YYYY-MM-DD" id="from_date" name="from_date" value="">

Enddate:<input size="16" type="text" placeholder="YYYY-MM-DD" id="to_date" name="to_date" onchange="calservicedays();" value="">

StartDate:2013-09-07 11:09:40

Enddate:2013-09-08 11:15:50

下面是我的javascript代码

function calservicedays(){
    var start = $("#from_date").val();
    var startDate = new Date(start);    
    var end = $("#to_date").val();
    var endDate = new Date(end);
    var startcom =  Date.parse(start);
    var endcom = Date.parse(end);
    var diff = Math.floor((endDate.getTime() - startDate.getTime()) / 86400000);
    if((startDate != null && endDate != null) && (start != '' && end != '')){
        if((startDate != null && endDate != null) && (start != '' && end != '') && (startcom < endcom)){
            var diff = Math.floor((endDate.getTime() - startDate.getTime()) / 86400000);
            if(diff != "")
              $("#service").val(diff);
        }else{
                alert("To Date cannot be less than or equal to From date");
                 $("#service").val('');
                return false;
            }
    }
 }

有了这个 javascript 代码,我就在几天之内得到了不同。我想要天和时间的差异。

谁能告诉我我必须在我的javascript代码中进行哪些更改才能获得日期和时间的差异。

谢谢

4

3 回答 3

1

使用日期对象很容易参考这个Date Nice Function

jsfiddle

var date1 = new Date("7/11/2010");
var date2 = new Date("12/12/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays);
于 2013-09-07T06:32:37.010 回答
1
var k=Math.round(Math.round(new Date(2013,09,08,11,15,50)-new Date(2013,09,07,11,09,40)) / 86400000);
var k1=Math.round(new Date(2013,09,08,11,15,50)-new Date(2013,09,07,11,09,40)) % 86400000;
var h=Math.round(k1/3600000);
var h1=k1%3600000;
var m=Math.round(h1/60000);
var m1=h1%60000;
var s=Math.round(m1/1000);
var s1=s%1000;
alert("diff" +k+"days"+h+"hours"+m+"minutes"+s+"seconds"+s1+"milliseconds");
于 2013-09-07T06:58:51.847 回答
1

尝试这个,

var start = $('#arr_date').datepicker('getDate');
var end   = $('#dep_date').datepicker('getDate');
var days   = (end - start)/1000/60/60/24;

$(function() {
  var start = $('#arr_date').val();
  var end = $('#dep_date').val();
  var diff = new Date(end - start);
  var days = diff/1000/60/60/24;
  $('#num_nights').val(days);  
});

var date_diff = Math.abs((date2.getTime() - date1.getTime())/86400000);
于 2013-09-07T06:35:18.083 回答