问题
I'm trying to get a date for flights from the user and the datepicker always sets the date as datetime object with the user's timezone, resulting in a wrong date sent to server.
tried to use ng-model-options="{ timezone: 'utc' }"
but then the user see the wrong date after choosing the date (the date displayed as a day before what the user chose).
How can I tell datepicker to completely ignore timezone - if not possible what can I do on FE / BE to convert this date to non timezone date ?
I know I can convert it to Posix on FE but once I do it the datepicker screams that it needs date object.
Thanks in advance...
回答1:
I had exactly same issue and I ended us using this code
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';
}
its from this other SO question How to JSON stringify a javascript Date and preserve timezone
来源:https://stackoverflow.com/questions/46073513/angular-material-datepicker-timezone-ignore