gpt4 book ai didi

javascript - 为什么 Chrome V8 JavaScript 引擎将 "TG-1"到 "TG-12"识别为有效日期/时间?

转载 作者:搜寻专家 更新时间:2023-11-01 04:34:33 24 4
gpt4 key购买 nike

我实现了一个 CSV 解析器来猜测每一列的类型格式,但我发现 JavaScript Date 类认为“TG-1”是一个有效的日期/时间。

这是 Chrome 支持的一些我以前从未见过的模糊日期格式吗?我不认为这是一个有效的日期,查看不同的日期 ISO 标准我还没有看到对此的引用。

Chrome 74 表示它是有效的。

Firefox 64 说它无效。

let validDate = true;
try{
d = new Date("TG-1");
d.toISOString()
}catch(e){
validDate = false
}
console.log(validDate);

任何字符串后跟 - 和数字 1-12 都被认为是有效的:

d = new Date("adsfadgag-12")//valid per V8

最佳答案

引用自V8 sourcecode :

Legacy dates:

Any unrecognized word before the first number is ignored.

Parenthesized text is ignored.

An unsigned number followed by ':' is a time value, and is added to the TimeComposer. A number followed by '::' adds a second zero as well. A number followed by '.' is also a time and must be followed by milliseconds.

Any other number is a date component and is added to DayComposer. A month name (or really: any word having the same first three letters as a month name) is recorded as a named month in the Day composer. A word recognizable as a time-zone is recorded as such, as is (+|-)(hhmm|hh:).

Legacy dates don't allow extra signs ('+' or '-') or umatched ')' after a number has been read (before the first number, any garbage is allowed).

Intersection of the two: A string that matches both formats (e.g. 1970-01-01) will be parsed as an ES5 date-time string - which means it will default to UTC time-zone. That's unavoidable if following the ES5 specification.

After a valid "T" has been read while scanning an ES5 datetime string, the input can no longer be a valid legacy date, since the "T" is a garbage string after a number has been read.

换句话说:这种行为并不是真正计划好的,只是某些浏览器在某个时候表现得像这样,因此必须保留这种奇怪的行为。 Date(...) 将尝试解析几乎所有内容而不会提示。

关于javascript - 为什么 Chrome V8 JavaScript 引擎将 "TG-1"到 "TG-12"识别为有效日期/时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56044829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com