Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - 新的Date()从无效的输入字符串中产生有效的日期[重复](new Date() producing valid date from invalid input string [duplicate])

When I pass "test 2" string in new Date(), I am getting an actual date, how?(当我在新的Date()中传递“ test 2”字符串时,我得到的是实际日期,怎么办?)

I am trying to whether it is a date or not.(我正在尝试是否是约会。)

 console.log(new Date("test 2")); 

  ask by Irfan Khan translate from so


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.(否则,不要。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...