How to calculate the difference between the server time and the user’s computer?

Asked

Viewed 808 times

12

I need to adapt my code to calculate the difference between the server time where the site is hosted and the user’s computer time so as not to overload my system.

I am mounting a table where I will show the time of another server and need to update every second.

So I have to get three dice:

  1. Time of the server where the site is hosted
  2. Device time that is accessing the site to know the difference between server time
  3. Difference of the third server that will be recalculated every second

The third item I have set in Javascript as follows:

<script>
var difJogo = (-145);
</script>

Means the game server is 145 seconds behind the site server (main reference).

To get the time of the site’s server I use:

<?php
date_default_timezone_set('America/Sao_Paulo');
$cH = date('G');
$cM = date('i');
$cS = date('s');
echo $cH .':'. $cM .':'. $cS;
?>

And to get user device time use:

<script>
function hat() {
    var sAg = ( Date.now() / 1000 ) % 86400;
}
</script>

What I can’t do is unite all these functions to get where I want. The time of the site server needs to be the basis of everything because there are people who access the site from different places in the world, so I want to define that the time is the same for everyone using São Paulo time zone.

The final logic is: Horário do servidor - Horário do dispositivo + Diferença do Jogo.

This requires a function to display the game server time and update every 1 second.

  • looks like q vc is using php serverside and js clientside. Do you want the data in the client or server? either way I would do an endpoint on the server that receives the client date, or that returns the server date pro client, depending on where Voce wants to use the end value

3 answers

3


It may not be the best solution, but the simplest way I could find to use PHP within Javascript as the goal of your question, would be that way:

<?php
    date_default_timezone_set('America/Sao_Paulo');
    $Sh = date('G');
    $sM = date('i');
    $sS = date('s');
    $rS = ($Sh*60*60)+($sM*60)+$sS;
?>

<script>
    var myVar = setInterval(function(){ funRelogio() }, 1);
    var tServ = <?php echo $rS; ?>;
    var hr = new Date();
    var secn = hr.getSeconds() + (60 * (hr.getMinutes() + (60 * hr.getHours())));

function funRelogio() {
    var difArcadia = (100);
    var dt = new Date();
    var secs = dt.getSeconds() + (60 * (dt.getMinutes() + (60 * dt.getHours())));
    var difT = tServ - secn;
    var hrArc = secs + difArcadia - difT;
    var hHarc = Math.floor(hrArc/3600%24);
    var hMarc = Math.floor(hrArc/60%60);
    var hSarc = Math.floor(hrArc%60);
    var result =  hHarc + ":" + hMarc + ":" + hSarc;
document.getElementById("hArc").innerHTML = result;
}
</script>

<p id="hArc"></p>

It seems to me that the above code worked to create a clock that checks the current server time when the page is loaded, using PHP, then using Javscript, we can capture the current user time and still use basic operations to calculate the difference of the hosting server, the user device and add the difference of the game server as requested.

To create the answer, I used as a basis this link about PHP within Javascript, and this link to format seconds in standard h:m:s.

I’m a layman on the subject, so feel free to edit or base my answer on a more appropriate solution.

  • exactly that, making a server call only once and converting the result to javascript, so it will not overload the site server (shared hosting), because what will be running is javascript

2

You are involving PHP (server-side) variables with Javascript (client-side) variables. You need to define a strategy - or you pass the variable Javascript pro PHP or the PHP pro Javascript variable.

I would prefer the latter method because it makes more sense to send information from the server to the client, and it seems to me that the opposite (Javascript for PHP) is done through unconventional methods (i.e., most methods seem gambiarras).

But because it is a game, it is important to think that if you leave information that is relevant to the logic of it (as seems to be the case of the time) in the client-side code, eventually a joker with some knowledge of Javascript will change variables to "cheat" in the game.

So try sending the Javascript client time to PHP this way:

<script>
if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
}

else{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

var PageToSendTo = "script_jogo.php?";
var MyVariable = "sAg";
var VariablePlaceholder = "horaDoCliente=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;

xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
</script>

This way, the client time will be sent to the server asynchronously (without updating the page in the browser). After that, your script_jogo.php should do the other time difference calculations, etc. Of course, still someone could try to send a different time - or even change the system time on the computer as "Cheat"; this type of case also needs to be well taken care of and predicted by script_jogo.php to capture something out of the ordinary.

My suggestion: in the game registration, the user must inform his location, and the time zone must then be saved in the database. This way, you would avoid all this time variable upload flow and manage everything via PHP on the server side.

1

You can simplify the problem by working with UTC hours. so you can work the dates via Timezone in both PHP and javascript.

PHP

In PHP use the function gmdate it will always return the date and time of Greenwich, and then can apply the Timezone as needed.

To make Timezone conversions just do:

// Cria um objeto com a data atual UTC
$dt = new DateTime(gmdate('Y/m/d H:i:s'), new DateTimeZone('UTC'));

// Altera a timezone
$dt->setTimezone(new DateTimeZone('America/Sao_Paulo'));

// format the datetime
$dt->format('Y-m-d H:i:s T');

Javascript

In javascript to convert UTC date to local do

var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // 1º forma
date.toLocaleString() // 2º forma

See here a documentation about the date functions in javascript

An answer on UTC date conversions to the local format

Browser other questions tagged

You are not signed in. Login or sign up in order to post.