nodejs构建的服务端,由于时区的问题会导致返回的日期不正确,为了修正日期问题,对Date增加全局的toJSON方法来修正此问题,代码如下: 注:如果使用的是express框架,则在app.js的首部增加如下代码,其他框架根据实际情况贴入即可 Date.prototype.toJSON = function () { var timezoneOffsetInHours = -(this.getTimezoneOffset() / 60); //UTC minus local time var sign = timezoneOffsetInHours >= 0 ? '+' : '-'; var leadingZero = (Math.abs(timezoneOffsetInHours) < 10) ? '0' : ''; //It's a bit unfortunate that we need to construct a new Date instance //(we don't want _this_ Date instance to be modified) var correctedDate = new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds()); correctedDate.setHours(this.getHours() + timezoneOffsetInHours); var iso = correctedDate.toISOString();//.replace('Z', '').replace('T',' ').replace(/\.[\d]+/g,''); return iso; };
nodejs 服务端时间问题
最新推荐文章于 2024-02-29 10:07:25 发布