Last active
March 20, 2017 16:29
-
-
Save NathanielInman/e9de4e7968497add53132ff36a107e31 to your computer and use it in GitHub Desktop.
Javascript new Date() in local time is wrong and how to fix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
new Date('2017-02-20').getDay() | |
=> 0 // February 20th of 2017 is a MONDAY not SUNDAY!!! | |
new Date('2017-02-20') | |
=> Sun Feb 19 2017 18:00:00 GMT-0600 (CST) //hmm... so its converting to local time? | |
new Date('2017-02-20 00:00:00') | |
=> Mon Feb 20 2017 00:00:00 GMT-0600 (CST) //aha! it is, so how do we fix it? | |
new Date(new Date('2017-02-20').getTime() + (new Date('2017-02-20').getTimezoneOffset() * 60000)) | |
=> Mon Feb 20 2017 00:00:00 GMT-0600 (CST) //yay! But that's too long... | |
new Date(new Date('2017-02-20').toUTCString().substr(0, 25)) | |
=> Mon Feb 20 2017 00:00:00 GMT-0600 (CST) //much better | |
new Date(new Date('2017-02-20').toUTCString().substr(0, 25)).getDay() | |
=> 1 // Finally. Seriously, they should adjust the Date object | |
new Date('2017-02-20').getUTCDay() | |
=> 1 // oh... (^_^) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDay