Javascript Date.toJSON没有得到时区偏移量

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)

但这有点过早优化,所以除非你在很短的时间内召唤它数千次,否则我不会打扰.

  • 由于时区偏移量以分钟为单位返回,您可以使用更简单和更短的`local.setMinutes(this.getMinutes() - this.getTimezoneOffset());`。另请注意,时区并非都是偶数小时(有些是 15 分钟),使用分钟将所有内容都保留为整数。至于性能,您需要在不同的浏览器中进行测试。但我怀疑除非你调用它数千次,否则速度没有实际意义。 (2认同)