Tutorial: Synchronize time

Step by stepTips 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 Flexible Datasync server. To get this value, you just have to listen on the path "[[baseUrl]]/base//.info/serverTimeOffset" like this :

var offsetRef = new Webcom("[[baseUrl]]/base/<your-webcom-app>/.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 Flexible Datasync server. This is usefull if you want to ensure consistent representation of time in your datas. When you read (or listen) values wrote 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 describe before to display the local time of your client.

var dataRef = new Webcom("[[baseUrl]]/base/<your-webcom-app>/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('[[baseUrl]]/base/<your-webcom-app>');

var offsetRef = new Webcom('[[baseUrl]]/base/<your-webcom-app>/.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...
});