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

12

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

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

So I have to get three data:

  • Server time where the site is hosted
  • Time of the device that is accessing the site to know the difference between the time of the server
  • Third server difference that will be recalculated every second
  • The third item I have defined in JavaScript as follows:

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

    It means that the game server is 145 seconds behind the site server (main reference).

    To get the time of the site 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 the time of the user's device I use:

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

    What I can not do is put all these functions together to get where I want to go. 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 set the time for everyone using the São Paulo time zone.

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

    With this, you need a function to display the time of the game server and refresh every 1 second.

        
    asked by anonymous 09.11.2017 / 21:30

    3 answers

    2

    It might not be the best solution, but the simplest way I found to use PHP within JavaScript was the purpose of your question, it would look like this:

    <?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>
    

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

    To create the answer, I used this link about PHP within JavaScript, and this link to format the seconds in the h: m: s pattern.

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

        
    20.11.2017 / 05:17
    1

    You are wrapping PHP (server-side) variables with Javascript (client-side) variables. You must define a strategy - or you pass the variable Javascript pro PHP or PHP variable Javascript Javascript . / p>

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

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

    So try to send the client's time from Javascript to PHP like this:

    <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>
    

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

    My suggestion: In the game registry, the user must inform his place, and the timezone should then be saved in the database. That way, you would avoid all this time variable upload flow and manage everything via PHP on the server side.

        
    13.11.2017 / 22:15
    1

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

    PHP

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

    To do 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 date from UTC 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 documentation on javascript date functions

    A response on conversions from UTC date to local format

        
    18.11.2017 / 07:06