[英]How can I change the timezone of a date without changing it's content?
We are working with another company that builds the back, and they are saving the date in this format:我们正在与另一家构建后台的公司合作,他们以这种格式保存日期:
"2020-12-12T12:00:00.0000Z" “2020-12-12T12:00:00.0000Z”
The thing is, when we create a Date object passing that date, it adds 2 hours to it (as we are in GMT+2), so when we try to compare to the current date it's never the same.问题是,当我们创建一个传递该日期的日期 object 时,它会增加 2 小时(就像我们在 GMT+2 中一样),因此当我们尝试与当前日期进行比较时,它永远不会相同。
So what we need is to transform that date to GMT+2 so we can compare dates, but without modifying the date it's initially displaying.所以我们需要将该日期转换为 GMT+2,以便我们可以比较日期,但不修改它最初显示的日期。
... it adds 2 hours to it... ...它增加了2个小时...
No, it doesn't.不,它没有。 It gives you a Date
representing the time the string defines.它为您提供了一个代表字符串定义时间的Date
。 The string has the Z
suffix meaning it's expressed in GMT/UTC.该字符串具有Z
后缀,表示它以 GMT/UTC 表示。 If you parse that, the result is a Date
object that represents that moment in time.如果你解析它,结果是一个代表那个时刻的Date
object。 In your timezone, the timezone-sensitive functions ( getHours
, getMinutes
, toString
) will use your timezone to provide appropriate values.在您的时区中,时区敏感函数( getHours
、 getMinutes
、 toString
)将使用您的时区来提供适当的值。 The UTC functions ( getUTCHours
, getUTCMinutes
, toUTCString
) will use UTC (GMT). UTC 函数( getUTCHours
、 getUTCMinutes
、 toUTCString
)将使用 UTC (GMT)。
If the backend is sending you that string and it's not meant to be in UTC, then the backend is sending you an incorrect string.如果后端向您发送该字符串并且它不是UTC 格式,那么后端向您发送的字符串不正确。
If you wanted to ignore the timezone indicator on the string and parse it as though it were local time, your best bet would be to break it into parts and use the new Date(year, month, day)
constructor.如果您想忽略字符串上的时区指示符并将其作为当地时间进行解析,最好的办法是将其分成几部分并使用new Date(year, month, day)
构造函数。 However, you could also just remove the Z
, as the specification says that date/time forms without a timezone indicator are parsed in local time (whereas date-only is UTC).但是,您也可以只删除Z
,因为规范说没有时区指示符的日期/时间 forms 是在本地时间解析的(而 date-only 是 UTC)。 The spec moved around a bit on this, though, which is why I suggest using the new Date(year, month, day)
constructor instead.不过,规范对此有所调整,这就是为什么我建议改用new Date(year, month, day)
构造函数。
Try to add moment for this purpose npm install moment-timezone --save
尝试为此添加时刻npm install moment-timezone --save
And in your code在你的代码中
var a = moment.tz("2020-12-12T12:00:00.0000Z", "Asia/Taipei");
a.format(); // 2020-12-12T12:55:00+08:00
Your zone for exmaple = Asia/Taipei例如,您所在的区域 = 亚洲/台北
Hope useful希望有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.