Skip to content

Instantly share code, notes, and snippets.

@blackjid
Created April 19, 2012 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackjid/2422261 to your computer and use it in GitHub Desktop.
Save blackjid/2422261 to your computer and use it in GitHub Desktop.
Create a Javascript date object with the time synced with the server time. The code must be processed in the server.
// Django template
(function(){
var _date = new Date();
date = {
gmtOffset: {% now "Z" %},
offset: {% now "U" %} - Math.round(_date.getTime() / 1000),
now: function(unix){
if(unix)
return Math.round(_date.getTime() / 1000) + this.offset + _date.getTimezoneOffset()*60*1000 + this.gmtOffset*1000;
return new Date(((Math.round(_date.getTime() / 1000) + this.offset)*1000) + _date.getTimezoneOffset()*60*1000 + this.gmtOffset*1000);
}
}
})();
// Php template with shorthand tags enabled
(function(){
var _date = new Date();
date = {
gmtOffset: <?= date('Z') ?>,
offset: <?=time()?> - Math.round(_date.getTime() / 1000),
now: function(unix){
if(unix)
return Math.round(_date.getTime() / 1000) + this.offset + _date.getTimezoneOffset()*60*1000 + this.gmtOffset*1000;
return new Date(((Math.round(_date.getTime() / 1000) + this.offset)*1000) + _date.getTimezoneOffset()*60*1000 + this.gmtOffset*1000);
}
}
})();
// Rails template
(function(){
var _date = new Date();
date = {
gmtOffset: <%= Time.current.gmt_offset =%>,
offset: <%= Time.current.to_i %> - Math.round(_date.getTime() / 1000),
now: function(unix){
if(unix)
return Math.round(_date.getTime() / 1000) + this.offset + _date.getTimezoneOffset()*60*1000 + this.gmtOffset*1000;
return new Date(((Math.round(_date.getTime() / 1000) + this.offset)*1000) + _date.getTimezoneOffset()*60*1000 + this.gmtOffset*1000);
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment