I use mongoose,
This is the Schema I defined:
const report = mongoose.Schema({
datetime: Date,
username: String,
detail: mongoose.Schema.Types.Mixed
})
This is the data I saved:
let params = {
username: 'testadmin',
detail: '23123',
datetime: new Date('December 17, 1995 03:24:00')
}
After saving into mongodb, the saving time will be eight hours earlier:
'3:00 a.m. on December 17, 1995' becomes 'December 16 At 7 o'clock in the evening today, the time zone is wrong. What should you do in this situation? Is there any corresponding processing method in mongodb or mongoose?
Thanks in advance, brother!
It turns out that mongodb stores UTC time, which is globally unified. Then save it directly. No operations are performed before saving. After reading it out, add the time new Date(report.datetime).toLocaleString() and call the js built-in Just Date().toLocaleString() will do
Because mongoose and sequelize did not consider the time zone when they started, and the ORM got the wrong time zone later. The solution is to see if it is solved in the latest version. If it is not solved yet, you can try sending the problem to the author. Then you can only preprocess it at the application layer yourself, writing +8 hours and reading -8.
Save it as a unix timestamp, so there won’t be any problems. When you take it out, just process the conversion according to the time zone
Just put the iso time back into new Date. The saved iso standard time will be automatically converted to the local time zone when you set new date
As a classmate above said, use ISO format: new Date("2017-03-02T08:00:00+08:00")
or
Using moment.js
For reference.
Love MongoDB! Have fun!
You can try to save the timestamp