Javascript - 两个日期之间的时间

时间:2014-04-24 16:56:10

标签: javascript

我一直试图制作一个计算两个时间戳之间时差的函数,例如。

Ex1: 23-04-2014 08:00:00
Ex2: 24-04-2014 12:56:40

经过一些研究后,我获得了部分成功,但我不知道如何在几小时内计算出日期。

因此,如果您明白我的意思,那么该功能应该超过24小时,我不想要x天。

代码

$(document).ready(function() {    
    function calculateTime() {
             var valuestart = "08:48:30";
             var valuestop = "17:56:37";

             var hourStart = new Date("01/01/2014 " + valuestart).getHours();
             var hourEnd = new Date("01/01/20014 " + valuestop).getHours();
             var hourDiff = hourEnd - hourStart;  

             var minStart = new Date("01/01/20014 " + valuestart).getMinutes();
             var minEnd = new Date("01/01/20014 " + valuestop).getMinutes();
             var minDiff = minEnd - minStart;

             var secStart = new Date("01/01/20014 " + valuestart).getSeconds();
             var secEnd = new Date("01/01/20014 " + valuestop).getSeconds();
             var secDiff = secEnd - secStart;

        if (hourDiff < 10) hourDiff = "0" + hourDiff;
        if (minDiff < 10) minDiff = "0" + minDiff;
        if (secDiff < 10) secDiff = "0" + secDiff;

        $("p").html("<b>Time difference:</b> " + hourDiff + ":" + minDiff + ":" + secDiff)             

    }
    calculateTime();
    });

这是我的小提琴:http://jsfiddle.net/Ma4sb/

1 个答案:

答案 0 :(得分:1)

试试这个,(并假设你的结束日期是一个错字):

$(document).ready(function() {    
    function calculateTime() {
         var valuestart = "08:48:30";
         var valuestop = "17:56:37";

         var dateStart = new Date("01/01/2014 " + valuestart);
         var dateEnd = new Date("01/01/2014 " + valuestop);
         var secDiff = (dateEnd - dateStart)/1000;   // in seconds.

         var hourDiff = Math.floor(secDiff / (60 * 60));

         secDiff -= hourDiff * 60 * 60;

         var minDiff = Math.floor(secDiff / 60);
         secDiff -= minDiff * 60;


         if (hourDiff < 10) hourDiff = "0" + hourDiff;
         if (minDiff < 10) minDiff = "0" + minDiff;
         if (secDiff < 10) secDiff = "0" + secDiff;

         $("p").html("<b>Time difference:</b> " + hourDiff + ":" + minDiff + ":" + secDiff)             

    }
    calculateTime();
});

http://jsfiddle.net/Ma4sb/2/

因此,举例来说,如果我们将dateEnd移至01/02/2014,您就会看到:

Time difference: 33:08:07

我认为 是你想要的。如果没有,您可以通过将小时数除以24来轻松转换为天数。