问题
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