views:

31

answers:

0

I'm currently working on some Javascript to synchronize the client side clock with our servers. I'm doing this by looking at the 'Date' header of any Ajax responses (it only has to be accurate to a few seconds).

To make the rest of the code work seamlessly with this Date function I want to override the native Date function in a decorator style so I can just enhance it with the calculated clock skew.

So far I have this (which seems to work):

var SystemDate = Date;
var ServerDate = function() {
  var a = arguments;
  switch(a.length){
    case 0:
      var system_date = new SystemDate();
      return new SystemDate(system_date - ServerDate.skew);
    case 1:
      return new SystemDate(a[0]);
    case 7:
      return new SystemDate(a[0],a[1],a[2],a[3],a[4],a[5],a[6]);
  }
};
ServerDate.parse = Date.parse;
ServerDate.UTC   = Date.UTC;
ServerDate.skew  = 0;
var Date = ServerDate;

Now whenever I get an Ajax respose I can adjust the skew property and all new instances of Date will have the adjusted value.

I'm really inviting criticism. There are a few things I'm not sure on:

  • Is this a good idea? - I'm not a Javascript programmer so I've no idea what sins I have just commited
  • How can I handle the different argument lengths more neatly - it seems very hacky
  • Copying the class methods UTC and parse seems very brittle
  • The new Date function now returns a date object on the console rather than the string representation.