sim*_*imo 9 javascript timezone date
那么问题是我使用的代码是这样的:
new Date().toJSON().slice(0, 10)
Run Code Online (Sandbox Code Playgroud)
把我的日期作为YYYY-MM-DD字符串,然后我在一些mysql查询和一些条件语句中使用它像参数.在一天结束时,我没有得到正确的日期,因为它仍然在前一天(我的时区偏移是+2/3小时).
我没有注意到这个toJSON方法没有考虑你的时区偏移,所以我最终得到了这个hacky解决方案:
var today = new Date();
today.setHours( today.getHours()+(today.getTimezoneOffset()/-60) );
console.log(today.toJSON().slice(0, 10));
Run Code Online (Sandbox Code Playgroud)
有更优雅的解决方案吗?
Rob*_*obG 13
ECMAScript中的日期对象是内部UTC.时区偏移用于本地时间.
Date.prototype.toJSON的规范说它使用Date.prototype.toISOString,它声明"时区总是UTC".您的解决方案正在做的是按时区偏移量抵消日期对象的UTC时间值.
考虑将自己的方法添加到Date.prototype,例如
Date.prototype.toJSONLocal = function() {
function addZ(n) {
return (n<10? '0' : '') + n;
}
return this.getFullYear() + '-' +
addZ(this.getMonth() + 1) + '-' +
addZ(this.getDate());
}
Run Code Online (Sandbox Code Playgroud)
如果您想要挤出额外的性能,以下应该更快:
Date.prototype.toJSONLocal = (function() {
function addZ(n) {
return (n<10? '0' : '') + n;
}
return function() {
return this.getFullYear() + '-' +
addZ(this.getMonth() + 1) + '-' +
addZ(this.getDate());
};
}())
Run Code Online (Sandbox Code Playgroud)
但这有点过早优化,所以除非你在很短的时间内召唤它数千次,否则我不会打扰.