Why does Javascript getYear() return 108?

2019-01-03 15:12发布

Why does this javascript return 108 instead of 2008? it gets the day and month correct but not the year?

myDate = new Date();
year = myDate.getYear();

year = 108?

14条回答
Root(大扎)
2楼-- · 2019-01-03 15:56

var date_object=new Date(); var year = date_object.getYear(); if(year < 2000) { year = year + 1900; } //u will get the full year ....

查看更多
可以哭但决不认输i
3楼-- · 2019-01-03 16:00

BTW, different browsers might return different results, so it's better to skip this function altogether and and use getFullYear() always.

查看更多
迷人小祖宗
4楼-- · 2019-01-03 16:03

use date.getFullYear().

This is (as correctly pointed out elsewhere) is a Y2K thing. Netscape (written before 2000) originally returned, for example 98 from getYear(). Rather than return to 00, it instead returned 100 for the year 2000. Then other browsers came along and did it differently, and everyone was unhappy as incompatibility reigned.

Later browsers supported getFullYear as a standard method to return the complete year.

查看更多
地球回转人心会变
5楼-- · 2019-01-03 16:04

It must return the number of years since the year 1900.

查看更多
欢心
6楼-- · 2019-01-03 16:10

It's dumb. It dates to pre-Y2K days, and now just returns the number of years since 1900 for legacy reasons. Use getFullYear() to get the actual year.

查看更多
Root(大扎)
7楼-- · 2019-01-03 16:11

Since getFullYear doesn't work in older browsers, you can use something like this:

Date.prototype.getRealYear = function() 
{ 
    if(this.getFullYear)
        return this.getFullYear();
    else
        return this.getYear() + 1900; 
};

Javascript prototype can be used to extend existing objects, much like C# extension methods. Now, we can just do this;

var myDate = new Date();
myDate.getRealYear();
// Outputs 2008
查看更多
登录 后发表回答