JavaScript 的 getYear() 和 getFullYear() 函数之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16296897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:07:21  来源:igfitidea点击:

What's the difference between JavaScript's getYear() and getFullYear() functions?

javascript

提问by Thilo

I was working with JavaScript's Dateobject, and somewhere for the first time I needed to extract the year part of the date. What I saw was a weird behavior. It returns 113instead of 2013and I can't figure out how these two numbers might be related, except that the last two numbers might be the same.

我正在使用 JavaScript 的Date对象,并且在某个地方我第一次需要提取日期的年份部分。我看到的是一种奇怪的行为。它返回113而不是2013,我无法弄清楚这两个数字可能如何相关,除了最后两个数字可能相同。

var date = new Date();
console.log(date.getYear()); // prints 113
console.log(date.getFullYear()); // prints 2013

How these functions are different? And why having a function to getFullYear? It just makes no sense to me to get partof a year.

这些功能有何不同?为什么有一个功能getFullYear参加一年对我来说毫无意义。

回答by Thilo

It just makes no sense to me to get part of a year.

参加一年对我来说毫无意义。

Back in the day, when memory was expensive and the Year 2000 was far in the future, it did make sense for people to represent 1975 as 75. In retrospect a short-sighted decision.

回到过去,当内存价格昂贵且 2000 年遥遥无期时,人们将 1975 年表示为 75 确实是有道理的。回想起来,这是一个短视的决定。

date.getFullYear() == date.getYear() + 1900

回答by SpaceCowboy

getYear() returns the year - 1900, This has been deprecated for a while now, it's best to use getFullYear()

getYear() 返回年份 - 1900,这已经被弃用了一段时间,最好使用 getFullYear()

回答by CuriousMind

Its a Y2K thing, basically getYearmethod returns the year minus 1900.

它是 Y2K 的事情,基本上getYear方法返回年份减去 1900。

so, I encourage to move over to getFullYear& use that instead.

所以,我鼓励转向getFullYear并使用它。