[英]Javascript getFullYear() Date method weird behavior
Can anyone explain why getFullYear does not return 2014? 任何人都可以解释为什么getFullYear不会返回2014年?
console.log(new Date('2014-01-01').getFullYear()) //2013
console.log(new Date('2014-01-01').getUTCFullYear()) //2014
The dateString of "March 7, 2014" returns a different date than "2014-03-07" unless the local time-zone is UTC.
除非本地时区为UTC,否则“2014年3月7日”的dateString将返回与“2014-03-07”不同的日期。 When converting a dateString of "March 7, 2014" the local time-zone is assumed.
转换dateString为“2014年3月7日”时,假定为本地时区。 When converting a dateString of "2014-03-07" the UTC time-zone is assumed.
转换dateString为“2014-03-07”时,假定为UTC时区。 This results in two different Date values depending on the format of the string that is being converted.
这会产生两个不同的Date值,具体取决于要转换的字符串的格式。
So when you ask it to parse "2014-01-01", you're getting the time in UTC. 因此,当您要求它解析“2014-01-01”时,您将获得UTC时间。
Then you call .getFullYear()
on your object, which uses local time. 然后在对象上调用
.getFullYear()
,它使用本地时间。 If you live in the Eastern US like I do, then it basically subtracts 4 hours from the internal time and returns the year. 如果你像我一样住在美国东部,那么它基本上从内部时间减去4小时并返回年份。
So here's what happens: 所以这是发生的事情:
.getFullYear()
is called and "1388534400000" is converted to local time .getFullYear()
并将“1388534400000”转换为本地时间 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
According to this : "The difference is when you specify a string in the format YYYY-MM-DD, you get a date that is 12am in the GMT timezone and when you specify a date in the format DD-MM-YYYY, you get a date that is 12am in your current timezone." 根据这一点 :“不同之处在于,当您以YYYY-MM-DD格式指定字符串时,您将获得格林威治标准时间区域的日期为12am,当您以DD-MM-YYYY格式指定日期时,您将获得在您当前时区的上午12点的日期。“
So basically since you are specifying News Years Day 2014 when it gets converted from GMT to your local time it believes it is 12-31-13 not 01-01-14. 因此,基本上因为您指定2014年新闻年,当它从GMT转换为您当地时间时,它认为它是12-31-13而不是01-01-14。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.