为什么Javascript评估为00而不是2000的2位数年份00? [英] Why does Javascript evaluate a 2-digit year of 00 as 1900 instead of 2000?

查看:146
本文介绍了为什么Javascript评估为00而不是2000的2位数年份00?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旧的网络应用程序,其中使用Javascript来验证某些日期。用户通常使用2位数的年份,最近我发现它正在评估00为1900而不是2000

I have an old web app where Javascript is used to validate some dates. Users usually use 2-digit years and I recently discovered it was evaluating 00 as 1900 instead of 2000

if (new Date(tb[0].value) > new Date(tb[1].value)){
    alert('Starting date must come before the ending date');
    tb[0].focus();
    return false;
}

在第一个框和1/1/00中输入1/1/99在第二次会导致一个错误消息,表示开始日期必须在结束日期之前,因为99在1999年进行评估,而00在1900年评估。

Entering 1/1/99 in the first box and 1/1/00 in the 2nd will cause an error message saying the start date has to be before the end date because 99 is evaluating at 1999 while 00 is evaluating at 1900.

当然,用户可以使用4位数的年份来解决这个问题,但是我仍然想知道可以做些什么来使JavaScript能够正确地评估两位数年份。

Of course, Users can get around this using 4-digit years, but I still want to know what can be done to get Javascript to evaluate 2-digit years correctly.

所以我的问题是,如何让Javascript来评估00为2000而不是1900?

So my question is, how can I get Javascript to evaluate 00 as 2000 and not 1900?

推荐答案

这样做是因为语言是在20世纪90年代(和匆忙)。您可以使用 getFullYear() setFullYear()以非愚蠢的方式处理年。

It does that because the language was created in the 1990's (and in a hurry). You can use getFullYear() and setFullYear() to handle years in a non-goofy way.

我所做的是写一些代码来检查年值小于100,如果它大于90(或类似的情况,根据情况,假设它在20世纪,否则假定是第21个。

What I've done is write some code to check for year values less than 100, and if it's greater than 90 (or something similarly appropriate, depending on the situation) assume it's in the 20th century, otherwise assume the 21st.

而@Rachel没有办法告诉运行时库的行为方式不同,至少没有任何标准化的方式。这就是日期代码的工作原理。

And @Rachel no there's no way to tell the runtime library to behave differently, at least not any standardized way. That's just how the Date code works.

这篇关于为什么Javascript评估为00而不是2000的2位数年份00?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆