Skip to content

Instantly share code, notes, and snippets.

@NathanielInman
Last active March 20, 2017 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NathanielInman/e9de4e7968497add53132ff36a107e31 to your computer and use it in GitHub Desktop.
Save NathanielInman/e9de4e7968497add53132ff36a107e31 to your computer and use it in GitHub Desktop.
Javascript new Date() in local time is wrong and how to fix
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... (^_^)
@NathanielInman
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment