Samson Samson - 3 months ago 27
HTML Question

How to make a condition of if client's time is not equal to server time? (let say 2 hours error)

I just used xml http request to get the current time of server.

The code is below:

var xmlHttp;
function srvTime(){
try {
//FF, Opera, Safari, Chrome
xmlHttp = new XMLHttpRequest();
catch (err1) {
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
catch (err2) {
try {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
catch (eerr3) {
//AJAX not supported, use CPU time.
alert("AJAX not supported");
xmlHttp.setRequestHeader("Content-Type", "text/html");
return xmlHttp.getResponseHeader("Date");

var st = srvTime();
var date = new Date(st);
var localTime = new Date();
document.write("Local machine time is: " + localTime + "<br>");
document.write("Server time is: " + date);

I set out two time, the first one is client local time, second one is server time.

The time pattern is like that (WeekDay Month Date Year HH:MM:SS TimeZone (Region)):

Local machine time is: Wed Nov 22 2017 15:44:00 GMT+0800 (HKT)

Server time is: Wed Nov 22 2017 14:44:02 GMT+0800 (HKT)

I need to make a if condition which is client's local time is not match the server time, let say if client's local time error more than 2 hours with server time, it will pop up an
alert("your time is not match!");

Answer Source

Here is my answer, js code:

var calcTimeError = (localTime.getTime() - date.getTime());
if(calcTimeError < -7200000 || calcTimeError > 7200000){
    //do something here (7200000 = 2 hours: 1000ms * 60 * 60 * 2)
    alert("your time is not match!");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download