Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time difference and convert into hours and minutes in javascript

I am having the time values as follows starttime like : 09:00:00 , endTime like : 10:00:00 ; here no date value is needed. so this values need to calculate difference and convert into hours and minutes,seconds.

I had tried with :

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

Some time am getting NaN and 1111111 some digit format.

How can I convert into HH:MM:SS, or any other way to find time difference.

like image 632
Dharmaraja.k Avatar asked Oct 25 '13 07:10

Dharmaraja.k


3 Answers

You can take a difference of the 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
like image 93
SheetJS Avatar answered Oct 18 '22 08:10

SheetJS


    var startTime = "09:00:00";
    var endTime = "10:30:00";
    
    var todayDate = moment(new Date()).format("MM-DD-YYYY"); //Instead of today date, We can pass whatever date        

    var startDate = new Date(`${todayDate} ${startTime}`);
    var endDate = new Date(`${todayDate } ${endTime}`);
    var timeDiff = Math.abs(startDate.getTime() - endDate.getTime());

    var hh = Math.floor(timeDiff / 1000 / 60 / 60);   
    hh = ('0' + hh).slice(-2)
   
    timeDiff -= hh * 1000 * 60 * 60;
    var mm = Math.floor(timeDiff / 1000 / 60);
    mm = ('0' + mm).slice(-2)

    timeDiff -= mm * 1000 * 60;
    var ss = Math.floor(timeDiff / 1000);
    ss = ('0' + ss).slice(-2)
    
    alert("Time Diff- " + hh + ":" + mm + ":" + ss);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.28.0/moment.min.js"></script>
like image 28
hongchae Avatar answered Oct 18 '22 06:10

hongchae


function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);

// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
   hours = hours + 24;

return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}
like image 41
Vijaya Varma Lanke Avatar answered Oct 18 '22 07:10

Vijaya Varma Lanke