Tutorial: Synchronize time

Tips and Tricks Synchronize time

How to synchronize client with Flexible Datasync server time

Sometimes you must want the time difference between the user device and the [[service]] server. To get this value, you just have to listen on the path "/.info/serverTimeOffset" like this :

var offsetRef = new Webcom("<your-webcom-app>").child(".info/serverTimeOffset");
var timeOffset=0;
var serverTime;
offsetRef.on("value", function(snap) {
  timeOffset = snap.val();
  console.log("server time offset changed :"+timeOffset);
  serverTime = new Date().getTime() + timeOffset;
  console.log("new server time is "+serverTime);
});

Write data with server timestamp

You can use the special variable "Webcom.ServerValue.TIMESTAMP" to store timestamp managed by the [[service]] server. This is useful if you want to ensure consistent representation of time in your data. When you read (or listen) values written with this constant, you must receive an integer of the timestamp (the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC). You can use the serverTimeOffset described before to display the local time of your client.

var dataRef = new Webcom("<your-webcom-app>").child("mypath");
dataRef.set({
    "value": "test",
    "time" : Webcom.ServerValue.TIMESTAMP
});
dataRef.on("changed", function(snapshot) {
  var data=snapshot.val();
  console.log("value '"+data.value+"' changed at'"+Date.new(data.time).toLocaleString());
});

Full example for a simple 'chat'

In the following code, we use Webcom.ServerValue.TIMESTAMP to store new message timestamp. When we display the message to the user we add the 'timeOffset', so for every user all messages seems to be timestamped from local device clock.

var messagesRef = new Webcom('<your-webcom-app>');

var offsetRef = messagesRef.child('.info/serverTimeOffset');
var timeOffset=0;
offsetRef.on("value", function(snap) {
  timeOffset = snap.val();
  console.log("server time offset changed :"+timeOffset);
});

// Function called to push message in Flexible Datasync
function addMessage(username, message) {
    messagesRef.push({
      text: message,
      name: username,
      time: Webcom.ServerValue.TIMESTAMP
    });
}

messagesRef.on('child_added', function (snapshot) {
  var data = snapshot.val();
  var message=data.text;
  var username=data.name || "anonymous";
  // Retreive the timestamp of the message and add the current time offset
  var date=new Date(data.time-timeOffset);

  // Now you just have to append the new message in you page...
});