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;
};
来自:https://blog.csdn.net/joney1/article/details/104229988?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&dist_request_id=561128c0-8601-4bc7-9dca-62e76969dfd8&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control