Skip to content

Instantly share code, notes, and snippets.

@huafu
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huafu/9867833 to your computer and use it in GitHub Desktop.
Save huafu/9867833 to your computer and use it in GitHub Desktop.
Forces all dates in the browser to use UTC
# force dates to be UTC
__timezoneOffset = (new Date).getTimezoneOffset() * 60 * 1000
__dateWrapper = (original) ->
->
unless @__hacked
@__hacked = yes
@setTime @getTime() - __timezoneOffset
try
res = original.apply @, arguments
catch err
@setTime @getTime() + __timezoneOffset
delete @__hacked
throw err if err
res
else
original.apply @, arguments
['getDate', 'getDay', 'getFullYear', 'getHours', 'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds',
'getTimezoneOffset', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes',
'setMonth', 'setSeconds', 'setYear', 'toLocaleDateString', 'toLocaleTimeString', 'toLocaleString'].forEach (name) ->
Date::[name] = __dateWrapper Date::[name]
Date::toString = Date::toUTCString
Date::toDateString = ->
y = "#{@getUTCFullYear()}"
@toUTCString().split(y).shift().replace /\s*$/, ''
Date::toTimeString = ->
y = "#{@getUTCFullYear()}"
(@toUTCString().split(y).pop() + y).replace /^\s*/, ''
Date::getTimezoneOffset = -> 0
(function(){
var __dateWrapper, __timezoneOffset;
__timezoneOffset = (new Date).getTimezoneOffset() * 60 * 1000;
__dateWrapper = function(original) {
return function() {
var err, res;
if (!this.__hacked) {
this.__hacked = true;
this.setTime(this.getTime() - __timezoneOffset);
try {
res = original.apply(this, arguments);
} catch (_error) {
err = _error;
}
this.setTime(this.getTime() + __timezoneOffset);
delete this.__hacked;
if (err) {
throw err;
}
return res;
} else {
return original.apply(this, arguments);
}
};
};
['getDate', 'getDay', 'getFullYear', 'getHours', 'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds',
'getTimezoneOffset', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes',
'setMonth', 'setSeconds', 'setYear', 'toLocaleDateString', 'toLocaleTimeString', 'toLocaleString'
].forEach(function(name) {
Date.prototype[name] = __dateWrapper(Date.prototype[name]);
});
Date.prototype.toString = Date.prototype.toUTCString;
Date.prototype.toDateString = function() {
var y;
y = "" + (this.getUTCFullYear());
return this.toUTCString().split(y).shift().replace(/\s*$/, '');
};
Date.prototype.toTimeString = function() {
var y;
y = "" + (this.getUTCFullYear());
return (this.toUTCString().split(y).pop() + y).replace(/^\s*/, '');
};
Date.prototype.getTimezoneOffset = function() {
return 0;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment