javascript - JS new Date() will be 8 hours earlier when saved in mongodb. We are in the East Eighth District and mongodb saves Greenwich time.
我想大声告诉你
我想大声告诉你 2017-06-05 11:08:46
0
7
1624

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!

我想大声告诉你
我想大声告诉你

reply all(7)
伊谢尔伦

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.

滿天的星座

The getTimezoneOffset() method returns the time difference between Greenwich Mean Time and local time, in minutes.

世界只因有你

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!