简体   繁体   中英

Why is JavaScript Date not updating after daylight savings?

JS Date Madness

What I'm expecting

I have node apps that send broadcasts to platforms such as Facebook messenger. A user subscribes to receive the broadcast at a set time eg 2pm daily.

The user gets saved to the database with a field nextQuoteDate with a Date object value modified to have the exact time when the app needs to send the next broadcast eg 2018-03-29T14:00:00.000Z . So the app checks for users to broadcast to with eg user.find({ nextQuoteData: {$lte: new Date()} }) and if the broadcast is sent this field gets an additional day: 2018-03-30T14:00:00.000Z .

What I'm now seeing

After daylight savings all my node apps are now sending the broadcasts an hour later. So instead of 2pm it's 3pm. This is because new Date() returns 2018-03-29T13:37:48.508Z when I'm expecting 2018-03-29T14:37:48.508Z .

Here's what I've been playing around with to try to understand this.

me$ date
Thu 29 Mar 2018 14:37:39 BST
me$ node
> Date()
'Thu Mar 29 2018 14:37:45 GMT+0100 (BST)'
> new Date()
2018-03-29T13:37:48.508Z
> new Date().toLocaleString()
'2018-3-29 14:38:02'
> new Date(new Date().toLocaleString())
2018-03-29T13:38:10.000Z
> new Date(new Date().toLocaleString() + ' GMT')
2018-03-29T14:38:15.000Z

But no solution yet. Any suggestions?

They aren't an hour behind.

Thu 29 Mar 2018 14:37:39 BST

2.37pm British Summer Time

'Thu Mar 29 2018 14:37:45 GMT+0100 (BST)'

2.37pm British Summer Time

2018-03-29T13:37:48.508Z

1.37pm UCT which is one hour behind BST which is correct

'2018-3-29 14:38:02'

2.38pm with no specified time zone (but you asked for the Locale Time so that will be BST)

2018-03-29T13:38:10.000Z

1.38pm UCT which is one hour behind BST which is correct

2018-03-29T14:38:15.000Z

2.38pm UCT which is one hour behind BST which is wrong because you hacked the wrong time zone into the string.


Converting time stamps to UCT is a very normal thing to do. It allows for them to be processed with consistency.

You might want to avoid having to explicitly format them (eg with toLocaleString ) for display to humans, but that isn't how the Date object works, so you'll have to live with it.

See the Z in the end? That indicates zero hour offset. The output is just the date normalized to 0 offset - it's an internationalization thing - JavaScript is actually correct and allowed to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM