我试图从用户那里获取航类日期,但日期选择器始终将日期设置为带有用户时区的日期时间对象,导致发送到服务器的日期错误。
尝试使用 ng-model-options="{ timezone: 'utc' }"
但是用户在选择日期后会看到错误的日期(该日期显示为用户选择的日期之前的一天)。
如何告诉日期选择器完全忽略时区 - 如果不可能,我可以在 FE/BE 上做什么来将此日期转换为非时区日期?
我知道我可以将它转换为 FE 上的 Posix,但是一旦我这样做,日期选择器就会尖叫它需要日期对象。
提前致谢...
最佳答案
我遇到了完全相同的问题,我最终使用了这段代码
Date.prototype.toJSON = function () {
var timezoneOffsetInHours = -(this.getTimezoneOffset() / 60); //UTC minus local time
var sign = timezoneOffsetInHours >= 0 ? '+' : '-';
var leadingZero = (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', '');
return iso + sign + leadingZero + Math.abs(timezoneOffsetInHours).toString() + ':00';
}
它来自另一个SO问题How to JSON stringify a javascript Date and preserve timezone
关于angularjs - Angular Material Datepicker 时区忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46073513/