如何计算两次之间的差异

时间:2014-11-06 10:13:00

标签: javascript time

在JavaScript中,我如何计算两次之间的差异。

示例:获取从01:30到3:30经过的小时数:分钟

下面我从下拉菜单中获取时间值并尝试计算两次之间的差异。

    <select name="timestart">
    <option value="00:00">00:00 am</option>
    <option value="00:30">00:30 am</option>
    <option value="01:00">01:00 am</option>
    </select>

Result must be like this: - 00:30-01:00 = 00:30

所以请提出解决方案。

3 个答案:

答案 0 :(得分:2)

试试这段代码:

 var timeStart = new Date("01/01/2007 " + x).getHours();

 var timeEnd = new Date("01/01/2007 " + y).getHours();

 var hourDiff = timeEnd - timeStart;

 var timeStartMin = new Date("01/01/2007 " + x).getMinutes();

 var timeEndMin = new Date("01/01/2007 " + y).getMinutes();

 var minutesDiff = timeEndMin - timeStartMin;

 alert("there are :"+hourDiff+":"+minutesDiff+" elapsed");

答案 1 :(得分:2)

尝试以下功能

function diff(startTime, endTime) {
startTime = startTime.split(":");
endTime = endTime.split(":");

var startDate = new Date(0, 0, 0, startTime[0], startTime[1], 0);
var endDate = new Date(0, 0, 0, endTime[0], endTime[1], 0);

var difference = endDate.getTime() - startDate.getTime();
var Hours = Math.floor(difference / 1000 / 60 / 60);

difference -= Hours * 1000 * 60 * 60;
var Minutes = Math.floor(difference / 1000 / 60);

if (Hours < 0)
   Hours = Hours + 24;

return Hours + ":" +  Minutes;
}

答案 2 :(得分:1)

类似这样的事情

    function calcola(){
    var start = document.getElementById("timeStart").value
    var end = document.getElementById("timeEnd").value

    var startv = start.split(":")
    var endv = end.split(":")

    var startm = startv[0]*60 + startv[1]*1
    var endm = endv[0]*60 + endv[1]*1

    var diffm = endm-startm
    var h = parseInt(diffm/60)
    var m = diffm % 60
    h = String(h).length == 1 ? "0"+h : h
    m = String(m).length == 1 ? "0"+m : m
    var ret = h + ":" + m
    return ret
}

<select name="timeStart" id="timeStart">
 <option value="00:00">00:00 am</option>
 <option value="00:30">00:30 am</option>
 <option value="01:00">01:00 am</option>
</select>
<select name="timeEnd" id="timeEnd">
 <option value="00:00">00:00 am</option>
 <option value="00:30">00:30 am</option>
 <option value="01:00">01:00 am</option>
...
 <option value="12:00">12:00 pm</option>
 <option value="13:00">01:00 pm</option>
 <option value="13:30">01:20 pm</option>
</select>
<input type="button" onclick="alert(calcola())">