简体   繁体   中英

How can I calculate the difference between two times

In JavaScript, how can I calculate the difference between two times.

Example: Get how many hours:minutes elapsed from 01:30 to 3:30

Below I'm getting time values from dropdown menus and trying to calculate the difference in between the two times.

    <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

so please suggest solution.

Try this code:

 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");

Try this below function

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;
}

something like this

    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
}

having

<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())">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM