Why does ISO date in Mongodb display one day earlier?

荒凉一梦 提交于 2021-02-07 10:32:23

问题


The stored date looks like this:

...
"date_of_birth" : ISODate("1920-01-02T00:00:00Z"),
...

Using moment, it is formatted in the model (in order to populate the input for updating the document) like this:

   AuthorSchema
   .virtual('date_of_birth_update_format')
   .get(function(){
      // format in JavaScript date format (YYYY-MM-DD) to display in input type="date"
      return this.date_of_birth ? moment(this.date_of_birth).format('YYYY-MM-DD') : '';
   });

Retrieved from the collection and displayed, it displays as one day earlier like this:

01/01/1920

I would appreciate any help to resolve this.


回答1:


The date from mongo is always in GMT, and your server might be in other timezone. You need to convert date to GMT before formatting.

var moment = require("moment-timezone")

AuthorSchema.virtual('date_of_birth_update_format').get(function(){
 return this.date_of_birth ? moment(this.date_of_birth).tz('GMT').format('YYYY-MM-DD') : '';
});



回答2:


The Z in the ISO 8601 format implies 'GMT' i.e. 1920-01-02T00:00:00+0000. Moment will take your timezone into consideration. If you are in the continental US, your time zone offset is -0400-0800.

1920-01-02T00:00:00Z = 1920-01-01T6:00:00-0600 In Pacific Standard Time for example.




回答3:


It depends on the time zone which you are in for example am in India so GMT for me is +5:30 so whenever I retrieve from db I would add up 5:30 to time so that it matches the date and to answer why it storing it a day before because it stores date in ISO format that's why



来源:https://stackoverflow.com/questions/46452658/why-does-iso-date-in-mongodb-display-one-day-earlier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!