计算2次之间的差异

时间:2014-02-26 22:56:36

标签: javascript jquery

我试图计算2个输入时间之间的差异但是我得到了分钟和秒的问题,因为当我得到差异时,我得到两者的十进制格式。这是我的代码http://jsfiddle.net/8deT5/4/

 $(function() {

var dNow = new Date();
var localdate= dNow.getHours() + ':' + dNow.getMinutes() + ':' + dNow.getSeconds();
var a = $("#start_hour_sch");
var b = $("#end_hour_sch");
var result = $("#hourdifference");


$( "#houradd" ).on( "click", function() {

    a.val(localdate);

});

$( "#hourend" ).on( "click", function() {

    b.val(localdate);

var diff = new Date("1970-1-1 " + b.val()) - new Date("1970-1-1 " + a.val());

var diffSeconds = diff/1000;
var HH = Math.floor(diffSeconds/3600);
var MM = Math.floor(diffSeconds%3600)/60;
var SS = Math.floor(diffSeconds%3600)/60;

var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM) + ":" + ((SS < 10)?("0" + SS):SS)

    result.val(formatted);

});


});

1 个答案:

答案 0 :(得分:0)

为第二个日期创建不同的值

$( "#houradd" ).on( "click", function() {
    var dNow = new Date();
var localdate= dNow.getHours() + ':' + dNow.getMinutes() + ':' + dNow.getSeconds(); 
    a.val(localdate);

});

$( "#hourend" ).on( "click", function() {
        var dNow = new Date();
var localdate= dNow.getHours() + ':' + dNow.getMinutes() + ':' + dNow.getSeconds();
    b.val(localdate);