Time difference and conversion to hours and minutes in javascript

I have time values ​​as follows start time: 09:00:00, endTime like: 10:00:00; here a date value is not required. therefore, these values ​​should calculate the difference and convert to hours, minutes, seconds.

I tried:

var test = new Date().getTime(startTime); var test1 = new Date().getTime(endTime); var total = test1 - test; 

For a while I get NaN and 1111111 some digital format.

How to convert to HH: MM: SS or any other way to find the time difference.

+6
source share
2 answers

You can distinguish between time values:

 var diff = test1.getTime() - test.getTime(); // this is a time in milliseconds var diff_as_date = new Date(diff); diff_as_date.getHours(); // hours diff_as_date.getMinutes(); // minutes diff_as_date.getSeconds(); // seconds 
+11
source
 var startTime = "09:00:00"; var endTime = "10:00:00"; var startDate = new Date("January 1, 1970 " + startTime); var endDate = new Date("January 1, 1970 " + endTime); var timeDiff = Math.abs(startDate - endDate); var hh = Math.floor(timeDiff / 1000 / 60 / 60); if(hh < 10) { hh = '0' + hh; } timeDiff -= hh * 1000 * 60 * 60; var mm = Math.floor(timeDiff / 1000 / 60); if(mm < 10) { mm = '0' + mm; } timeDiff -= mm * 1000 * 60; var ss = Math.floor(timeDiff / 1000); if(ss < 10) { ss = '0' + ss; } alert("Time Diff- " + hh + ":" + mm + ":" + ss); 
+3
source

Source: https://habr.com/ru/post/956697/


All Articles