Search code examples
javascriptphpgoogle-chromedatetimeopera

JavaScript - How can i get the correct time of PHP server?


I need to show a timer central to PHP SERVER DATE, here which is date1. (Its about a meeting which was set in Belgium time and others from different country joins the meeting to see duration of the meeting realtime.)

date1 variable value coming from PHP server located in Belgium. But the users are in USA, Middel east, Asia, Australia, and there Browser date is not same as PHP server date.

How can i get the date2 value without crawling to server as Belgium date/time? so that i can show the gape realtime on date2.

var date1 = new Date("10-01-2016 09:00:00"); // Meeting at PHP SERVER date 
var date2 = new Date("10-01-2016 09:30:32"); // User joined remotely but Browser date is wrong here

var diff = date2.getTime() - date1.getTime();
var msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;

alert(hh + ":" + mm + ":" + ss);

Solution

  • I think you could use this answer: Getting the client's timezone in JavaScript to get the client (browser) timezone offset, the php server could sent this information along with date1, and from here it's easy to convert as you already did.

    Another approach could be that the server also sends the current time (similar to what the Date http header could be) and the client could save in a variable the time on the client at the moment it got the http, then calculate the difference between the server clock and client clock. This way it could not only calcualte that 9AM in Belgium is 2AM in New York, but also display a counter on the client that would be synchronized to the server time (meaning even if the client's clock is off by 2 minutes, the counter could be accurate to the server's clock, and so all the people would see the same counter, no matter of their client clock's inaccuracy (which is a nice feature even if we don't think of different timezones))

    So in your php besides date1="10-01-2016 09:00:00" you would also send

    server_date="<?php date('...') ?>"
    

    Use http://php.net/manual/en/function.date.php for the format string :)

    Then in javascript at the very beginning of the onLoad callback you would do:

    client_date = new Date();
    

    Now you can do your arithmetic (in pseudo code):

    elapsed_since_start = date1 + (server_date - client_date)
    

    Of course if you need to take into account the different timezones then you'll need to account for that too:

    elapsed_since_start = (date1-server_tz_offset) + ((server_date-server_tz_offset) - (client_date-client_tz_offset))