blackjid
4/19/2012 - 4:53 PM

Create a Javascript date object with the time synced with the server time. The code must be processed in the server.

Create a Javascript date object with the time synced with the server time. The code must be processed in the server.

// 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);
	    }
	}
})();
// 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);
	    }
	}
})();
// 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);
	    }
	}
})();