Skip to content Skip to sidebar Skip to footer

Time Sync Between Server & Browser

I am working on a live feed for a company which displays the status of their production schedule over the current 24 hour period. The issue is that some of the employees need to be

Solution 1:

Server time should be in UTC. That way, it's easier to move timezones.

Don't rely on the client for timezone since it depends on the client's machine, which could be set to any time and timezone. Have an account that requires a timezone. Use that for timezone offsets. Same reason why online services ask you your timezone instead of detecting it.

Then you can either go for interval sync, or sockets. Do note that latency could delay it by a few seconds.

Interval sync

You can have the server provide the initial time and timezone offset. Calculate the client's initial time based on those initial data, and have the client-side do the ticking. Since the script can go out of sync, you sync to the server periodically, like every 5 mins or so.

Sockets

Have the server calculate the user's time at his timezone, and send it down the line via sockets every second. All you need to do in the client side is display it.

Solution 2:

Directly from the MDN website:

var x = newDate();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;

This will get you the timezone offset in minutes between UTC and local time (the above example divides by 60 to convert to hours). This will already account for daylight savings time.

If your server puts the server timezone offset in a variable in the page or sends it with the live data or if the live data is in UTC time, then you can calculate the difference between the client and the data.

Solution 3:

Give your users the option to select the timezone they are in (via a dropdown or options page) and set it with php's native function date_default_timezone_set.

date_default_timezone_set("Europe/Brussels");

Then the time difference between the host server and the user is calculated automatically and daylight savings is also taken care of.

The documentation is here: https://php.net/manual/en/timezones.php

Then display the times using php's date function:

date("c"); // ISO 8601 date

Post a Comment for "Time Sync Between Server & Browser"