[英]JavaScript/NodeJS - Mongo DB gets Dates with offsets (timezone)
We are loading Dates from a Mongo database. 我们正在从Mongo数据库中加载日期。 It seems that Mongo saves everything in UTC, but when JS creates Date objects (for display this dates) it adds/substracts the timezone offset. 似乎Mongo将所有内容保存为UTC,但是当JS创建Date对象(用于显示此日期)时,它将添加/减去时区偏移量。 The result is, for example: 结果是例如:
As you see, I can get even different DAYS that the ones I wanted to save. 如您所见,我可以获得想要保存的不同日期。 I saw a few similar cases but nothing with this same technologies, I'm using Nodejs, MongoDB and Backbone. 我看到了一些类似的案例,但是使用相同的技术却一无所获,我正在使用Nodejs,MongoDB和Backbone。 Right now I'm doing something like this: 现在我正在做这样的事情:
parse: function(response) {
var dateStart = new Date(response.time.start);
var offset = dateStart.getTimezoneOffset() * 60000;
response.time.start = new Date(dateStart.valueOf() + offset);
return response;
}
But it's really ugly and I have to do it every time I instantiate a new Date() 但这真的很丑,每次实例化一个新的Date()时我都必须这样做
Anybody know a nice way to fix this? 有人知道解决此问题的好方法吗?
So sadly when you instantiate a Date object in a web browser, it will be in the browser's local time zone. 因此,令人遗憾的是,当您在Web浏览器中实例化Date对象时,该对象将位于浏览器的本地时区中。 Sometimes this helps, sometimes not. 有时这有帮助,有时则无济于事。 You can use moment.js moment.utc(myDate)
to handle this and keep things in UTC. 您可以使用moment.js moment.utc(myDate)
进行处理,并将其保留在UTC中。 In general I highly recommend moment.js for your go-to Swiss Army knife of date related code. 总的来说,我强烈建议您在与日期相关的瑞士军刀代码中使用moment.js。
Another approach would be to change your client to not submit fields to the server unless their value has truly changed. 另一种方法是更改您的客户端,使其不向服务器提交字段,除非它们的值确实发生了变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.