gpt4 book ai didi

Javascript 日期允许无效数据(例如 2 月 30 日)

转载 作者:数据小太阳 更新时间:2023-10-29 05:54:16 26 4
gpt4 key购买 nike

<分区>

如何验证日期?我的意思不是格式,而是逻辑。例如:2 月 30 日不是有效日期。

var date = new Date("2015-02-29T13:02:49.073Z"); // 2015 Feb 29th does not exist
console.log(date.toISOString());

Returns 2015-03-01T13:02:49.073Z (March 1st).

但是我想知道这个日期(输入)是无效的。

编辑:在 Chrome 中测试。 Firefox 返回“无效日期”。但不是在解析。只有在使用日期时(例如 toISOString())才会抛出异常。

try
{
var date = new Date("2015-02-29T13:02:49.073Z");
console.log(date.toISOString());
}
catch(e)
{
console.log("error: " + e.message);
}

火狐:

invalid date

Chrome :

(nothing, just switched to the next date.)

总结:它依赖于浏览器。所以,不推荐使用。

jsfiddle example

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