Javascript getFullYear() Date method weird behavior
javascript
Solution
From MDN:
The dateString of "March 7, 2014" returns a different date than "2014-03-07" unless the local time-zone is UTC. When converting a dateString of "March 7, 2014" the local time-zone is assumed. When converting a dateString of "2014-03-07" the UTC time-zone is assumed. This results in two different Date values depending on the format of the string that is being converted.
So when you ask it to parse "2014-01-01", you're getting the time in UTC.
Then you call `.getFullYear()` on your object, which uses local time. If you live in the Eastern US like I do, then it basically subtracts 4 hours from the internal time and returns the year.
So here's what happens:
- "2014-01-01" is converted to "1388534400000"
- `.getFullYear()` is called and "1388534400000" is converted to local time
- Local time is something like "1388534160000"
- New years hasn't yet occurred at "1388534160000", so it's still 2013
All of this implies that if we do something like
console.log(new Date('January 1, 2014').getUTCFullYear()); // 2014
console.log(new Date('January 1, 2014').getFullYear()); // 2014
We'll get the same year, because we told the browser to use our timezone right on New Year's, but they're not equivalent:
console.log(new Date('January 1, 2014').getUTCHours()); // 5
console.log(new Date('January 1, 2014').getHours()); // 0
Problem
Can anyone explain why getFullYear does not return 2014? ``` console.log(new Date('2014-01-01').getFullYear()) //2013 console.log(new Date('2014-01-01').getUTCFullYear()) //2014 ```