How would you check time difference from two text-boxes in Javascript?
I would use just getTime();
and for example Date.now()
to return difference in milliseconds:
//specified date:
var oneDate = new Date("November 02, 2017 06:00:00");
//number of milliseconds since midnight Jan 1 1970 till specified date
var oneDateMiliseconds = oneDate.getTime();
////number of milliseconds since midnight Jan 1 1970 till now
var currentMiliseconds = Date.now();
//return time difference in miliseconds
alert(currentMiliseconds-oneDateMiliseconds);
You can use moment js for this purpose. momentJs 'fromNow()' will give you any time difference from current time.
var m1 = any date time on moment format;
console.log(m1.fromNow());
Here's the solution that worked for me:
var date1 = new Date("08/05/2015 23:41:20");
var date2 = new Date("08/06/2015 02:56:32");
var diff = date2.getTime() - date1.getTime();
var msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;
alert(hh + ":" + mm + ":" + ss);
A good solution is avaliable at
http://blogs.digitss.com/javascript/calculate-datetime-difference-simple-javascript-code-snippet/
gives the output in your desired differnece format of
days : hours : minutes : seconds .
A slightly modified version of that code is shown below
var vdaysdiff; // difference of the dates
var vhourDiff;
var vmindiff;
var vsecdiff;
vdaysdiff = Math.floor(diff/1000/60/60/24); // in days
diff -= vdaysdiff*1000*60*60*24;
vhourDiff = Math.floor(diff/1000/60/60); // in hours
diff -= vhourDiff*1000*60*60;
vmindiff = Math.floor(diff/1000/60); // in minutes
diff -= vmindiff*1000*60;
vsecdiff= Math.floor(diff/1000); // in seconds
//Text formatting
var hourtext = '00';
if (hourDiff > 0){ hourtext = String(hourDiff);}
if (hourtext.length == 1){hourtext = '0' + hourtext};
var mintext = '00';
if (mindiff > 0){ mintext = String(mindiff);}
if (mintext.length == 1){mintext = '0' + mintext};
//shows output as HH:MM ( i needed shorter duration)
duration.value= hourtext + ':' + mintext;
The time diff in milliseconds
firstDate.getTime() - secondDate.getTime()
grab the input values after form submission in php
$start_time = $_POST('start_time');
$end_time =$_POST('end_time');
$start = $start_time;
$end = $end_time;
$datetime1 = new DateTime($end);
$datetime2 = new DateTime($start);
//echo $datetime1->format('H:i:s');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%h:%i');
$time = explode(":",$elapsed);
$hours = $time[0];
$minutes = $time[1];
$tminutes = $minutes + ($hours*60);
the variable $tminutes is total diff in minutes , working hour is $hour . this code is for php use this logic and convert this code to js