Passing a string to new Date
is the same as using Date.parse
.(将字符串传递给new Date
与使用Date.parse
相同。)
When a non-standard date string is passed, the result is implementation-dependent;(当传递非标准日期字符串时,结果取决于实现;)
the browser can do whatever it wants, including guessing .(浏览器可以做任何想做的事情,包括猜测 。) On Chrome, your input results in a date, but not on Firefox ( NaN
is returned).(在Chrome上,输入的结果是日期,但在Firefox上则没有(返回NaN
)。)
test
isn't part of a date string, so it looks like Chrome just parses the 2:(test
不是日期字符串的一部分,因此Chrome似乎只解析2:)
console.log(new Date('2')); console.log(new Date('1')); console.log(new Date('0'));
Essentially, this is undefined behavior , so strange results aren't surprising.(本质上,这是未定义的行为 ,因此奇怪的结果不足为奇。)
Unless the passed string conforms to the format defined in the specification - that is, something like "2011-10-10"
or "2011-10-10T14:48:00"
or "2011-10-10T14:48:00.000+09:00"
, the results are unpredictable.(除非传递的字符串符合规范中定义的格式 ,即类似"2011-10-10"
或"2011-10-10T14:48:00"
或"2011-10-10T14:48:00.000+09:00"
,结果不可预测。)
Consider instead figuring out what sort of string format you'd be expecting as an input, and then checking if the format is followed with a regular expression.(考虑改为找出您希望输入的字符串格式,然后检查该格式是否带有正则表达式。)
If so, pass to new Date
and see if it gives you a meaningful results;(如果是这样,传递给new Date
,看看它是否给您有意义的结果;) otherwise, don't.(否则,不要。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…