Angular Material Datepicker Timezone 忽略? [英] Angular Material Datepicker Timezone ignore?

查看:29
本文介绍了Angular Material Datepicker Timezone 忽略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从用户那里获取航班的日期,而日期选择器总是将日期设置为带有用户时区的日期时间对象,从而导致发送到服务器的日期错误.尝试使用 ng-model-options="{ timezone: 'utc' }"

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).

如何告诉 datepicker 完全忽略时区 - 如果不可能,我可以在 FE/BE 上做什么才能将此日期转换为非时区日期?

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 ?

我知道我可以在 FE 上将它转换为 Posix,但是一旦我这样做了,日期选择器就会尖叫它需要日期对象.

I know I can convert it to Posix on FE but once I do it the datepicker screams that it needs date object.

提前致谢...

推荐答案

我遇到了完全相同的问题,我结束使用此代码

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';
}

来自另一个 SO 问题 如何 JSON 字符串化 javascript 日期并保留时区

its from this other SO question How to JSON stringify a javascript Date and preserve timezone

这篇关于Angular Material Datepicker Timezone 忽略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆