jquery - JavaScript incorrect time showing between two time -
i have tried show time between 2 time while page load. please check below code -
var start = document.getelementbyid("start").value; var end = document.getelementbyid("end").value; function hourdiff(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); return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes; //settimeout(function(){hourdiff(start, end)},500); } document.getelementbyid("diff").value = hourdiff(start, end);
<input id="start" value="20:00"> <!-- 08.00 pm --> <input id="end" value="09:30"> <!-- 09.30 --> <input id="diff">
i have used start time 20.00
, end time 09.30
different between 2 time = 13.30
hours showing wrong hour. please check , let me know.
edit:
also want how many hour:minute:second
left
if dates in same format hh:mm, why don't try suggestion.
it quite simple:
var hours = end[0] - start[0]; if(start[0] > end[0]) { hours = 24 + hours; } var minutes = end[1] - start[1]; if(start[1] > end[1]) { minutes = 60 + minutes; if(hours == 0) { hours = 23; } else { hours--; } }
i substract them each other , react if start value bigger end value. fiddle: https://jsfiddle.net/rvwr9h0w/1/
edit
i found simpler solution, because of shotgun ninja's post:
https://jsfiddle.net/rvwr9h0w/4/
var enddate = new date(0, 0, (start > end)?1:0 , end[0], end[1], end[2]);
if start time bigger end time, set end date 1 day ahead.
Comments
Post a Comment