Monkeypatch JavasScript日期对象 [英] Monkeypatch the JavasScript date object
问题描述
我知道这是一个疯狂的黑客,但是无论如何好奇。我们有一个系统时间错误的环境,我们无法将其设置到正确的时间。它是专门的硬件,所以我们不能改变系统时间。然而,我们有一个服务,给我们正确的当前时间。我们的问题是,一堆ssl和令牌签名库破坏,因为他们从JavaScript Date对象得到错误的datetime(因为我们有错误的系统时间)。
I know that this a crazy hack but curious about it anyhow. We have an environment that has the wrong system time and we cannot set it to the correct time. It's specialized hardware so we cannot change the system time. We do however have a service that gives us the correct current time. Our issue is that a bunch of ssl and token signing libraries break because they are getting the wrong datetime from the javascript Date object ( since we have the wrong system time).
调用Date对象的构造函数的方式是什么,以便我们可以为它提供正确的初始化时间,以便所有后续对依赖库中Date(),Date.toString()等的调用将返回我们的新方法这会返回正确的非系统时间?
What's the way to monkeypatch the Date object's constructor so that we can feed it the correct time to initialize with so that all subsequent calls to Date(), Date.toString(), etc... in the dependent libraries will return our new method that returns the correct non-system time?
这个工作吗?
var oldDate = Date;
Date = function(){
return new oldDate(specialCallToGetCorrectTime());
}
Date.prototype = oldDate.prototype;
推荐答案
Will this work?
不,因为它不尊重你新的 Date 函数的参数或者是否被称为构造函数vs不是。另外你忘了修复
Date.now()
。你仍然需要得到正确的:
No, since it does not respect arguments given to your new Date
function or whether it was called as a constructor vs not. Also you forgot to fix Date.now()
. You still will need to get those right:
Date = (function (oldDate, oldnow) {
function Date(year, month, date, hours, minutes, seconds, ms) {
var res, l = arguments.length;
if (l == 0) {
res = new oldDate(Date.now());
} else if (l == 1) {
res = new oldDate(year); // milliseconds since epoch, actually
} else {
res = new oldDate(
year,
month,
l > 2 ? date : 1,
l > 3 ? hours : 0,
l > 4 ? minutes : 0,
l > 5 ? seconds : 0,
l > 6 ? ms : 0)
}
if (this instanceof Date) {
return res;
} else {
return res.toString();
}
}
Date.prototype = oldDate.prototype; // required for instanceof checks
Date.now = function() {
return oldnow() + offset; // however the system time was wrong
};
Date.parse = oldDate.parse;
Date.UTC = oldDate.UTC;
return Date;
})(Date, Date.now);
这篇关于Monkeypatch JavasScript日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!