JSFiddle - React, Tailwind, and code Playground
HTML
<h5>Method One</h5>
<script src="http://bruneigeekmeet.com/so/datediff.php?varname=mysql_data"></script>
<div id="timer"></div>
<h5>Method Two : Calculate Seconds in Server</h5>
<div id="timer2"></div>
<h5>Method Three : <code>performace.now()</code></h5>
<div id="timer3"></div>
JavaScript
//need a live page that outputs sql now(). has current time and time in two hours in server_time_in_two_hours
function timeDiff(target) {
function z(n) {return (n<10? '0' : '') + n;}
var timeDiff =target-Date.now()
var hours = timeDiff / 3.6e6 | 0;
var minutes = timeDiff % 3.6e6 / 6e4 | 0;
var seconds = timeDiff % 6e4 / 1e3 | 0;
if (hours<0 || minutes<0 || seconds<0) {
return '<b>EXPIRED</b>';
}
else {
return '<b>' + z(hours) + '</b> Hours, <b>' + z(minutes) + '</b> Mins, <b>' + z(seconds) + '</b> Secs';
}
}
var target=Date.parse(mysql_data.server_time_in_two_hours)-(Date.parse(mysql_data.now)-Date.now())
setInterval(function(){
timer.innerHTML=timeDiff(target)
},1000)
/*
SQL to achive this
http://sqlfiddle.com/#!9/665f5/1
create table test(
end_time datetime
);
insert into test values(now() + interval 10 hour ); #test_data
#select that outputs seconds left in server side
select timestampdiff(SECOND,now(),end_time) seconds_left from test
*/
var mysql2_data=[{"seconds_left":"600000"}]
var client_start=Date.now()
function timeDiff_fromseconds(target) {
function z(n) {return (n<10? '0' : '') + n;}
var timeDiff =target-(Date.now()-client_start)
var hours = timeDiff / 3.6e6 | 0;
var minutes = timeDiff % 3.6e6 / 6e4 | 0;
var seconds = timeDiff % 6e4 / 1e3 | 0;
if (hours<0 || minutes<0 || seconds<0) {
return '<b>EXPIRED</b>';
}
else {
return '<b>' + z(hours) + '</b> Hours, <b>' + z(minutes) + '</b> Mins, <b>' + z(seconds) + '</b> Secs';
}
};
setInterval(function(){
timer2.innerHTML=timeDiff_fromseconds(mysql2_data[0].seconds_left,client_start)
},1000);
/* perfomance.now polyfill from https://gist.github.com/paulirish/5438650*/
(function(){
if ("performance" in window == false) {
window.performance = {};
}
Date.now = (Date.now || function () { // thanks IE8
return new Date().getTime();
});
if ("now" in...