razvee
razvee

Reputation: 33

I need server time, not Local time (JavaScript)

I have a website (www.Best11.org) and I tried to put the server time in the footer with JavaScript. I thought everything is fine, but some users told me that it's local time actually, instead of server time...

Here's the script...

<script type='text/javascript'>
    var serverTime = <?php echo time() * 1000; ?>;
    var localTime = +Date.now();
    var timeDiff = serverTime - localTime;

    setInterval(function () {
        var realtime = +Date.now() + timeDiff;
        var date = new Date(realtime);
        // hours part from the timestamp
        var hours = date.getHours();
        if (hours < 10)
            hours = "0" + hours
        var minutes = date.getMinutes();
        if (minutes < 10)
            minutes = "0" + minutes
        var seconds = date.getSeconds();
        if (seconds < 10)
            seconds = "0" + seconds

        var formattedTime = hours + ':' + minutes + ':' + seconds;
        document.getElementById('clock').innerHTML = formattedTime;
    }, 1000);
</script>

What's wrong? :|

Upvotes: 2

Views: 1666

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

time returns the Unix timestamp. So what you're doing is showing the server's clock time on the client, but in their timezone.

If you want to show the server's current time, you need to use server local time for the value you pass to the JavaScript code. In this example, I've used getdate to get the local date/time on the server, and then built a call to the Date constructor for the client-side code, to get the offset between them:

var serverTime = new Date(
    <?php $now = getdate();
          echo $now['year']  . ',' . ($now['mon'] - 1) . ',' . $now['mday'] . ',' .
               $now['hours'] . ',' . $now['minutes']   . ',' . $now['seconds'];
?>);
var localTime = Date.now();
var timeDiff = serverTime.getTime() - localTime;

The rest of the script is unchanged.

I don't do a lot of PHP, I wouldn't be surprised if you can get your current timezone offset and do the math on the value from time instead. But the fundamental answer is that you weren't allowing for the server's timezone in what you sent the client, which is why it seemed to show the client's time (just according to the clock of the server).

Upvotes: 1

Related Questions