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!
伊谢尔伦2017-06-05 11:10:46
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
漂亮男人2017-06-05 11:10:46
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.
滿天的星座2017-06-05 11:10:46
The getTimezoneOffset() method returns the time difference between Greenwich Mean Time and local time, in minutes.
世界只因有你2017-06-05 11:10:46
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
PHP中文网2017-06-05 11:10:46
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
我想大声告诉你2017-06-05 11:10:46
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!