简体   繁体   English

JavaScript / NodeJS-Mongo DB获取带偏移的日期(时区)

[英]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: 结果是例如:

  • If I save the date "2013-06-20 01:00:00" 如果我保存日期“ 2013-06-20 01:00:00”
  • The date will be later auto-completed in a form as "2013-06-19 22:00:00" (Example for Argentina Time Zone UTC-03:00), and if the user saves that form without changing the date, the date will be saved with that wrong time. 日期将稍后以“ 2013-06-19 22:00:00”的形式自动完成(例如,阿根廷时区UTC-03:00的示例),如果用户保存该表单而不更改日期,则日期将以错误的时间保存。
  • Worst that that, the next save will substracts 3 hours MORE, and so on! 更糟糕的是,下一次保存将减去3小时,依此类推!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM