如果日期不正确,则返回 null

Return null if incorrect date

提问人:user2522570 提问时间:6/8/2023 最后编辑:user2522570 更新时间:6/9/2023 访问量:49

问:

我有很多变量——年、月、日。我正在尝试将其转换为正确的日期形式。如果变量的日期不正确,我想得到空

var year = "2023";
var month = "11"
var day = "31"
var date = new Date(year, month - 1, day);

// Log to console
console.log(date)

此代码返回 2023 年 12 月 1 日。但我想得到空值。我该怎么做?

编辑 我编辑了我的代码。我有 30/11、29/02、31/04 等日期不是有效日期

JavaScript 日期解析

评论

1赞 0stone0 6/8/2023
请添加更多详细信息,这是一个有效日期,你为什么要空?
3赞 Barmar 6/8/2023
new始终返回指定类的实例,它永远不会返回 。null
4赞 Barmar 6/8/2023
对象会自动处理日期溢出。如果天数大于指定月份的天数,则该天数将换行到下个月。因此,11 月 31 日不被视为错误,这只是 12 月 1 日的另一种说法。Date
3赞 Barmar 6/8/2023
这是经过深思熟虑的,它允许您执行日期算术,而无需自己处理日/月/年之间的交叉。
1赞 Salman A 6/9/2023
将结果的年、月、日与输入值进行比较。他们需要匹配。简单。

答:

1赞 Sai Manoj 6/9/2023 #1

您可以添加一个条件来检查日期是否有效

var year = "2023";
var month = "5";
var day = "32";

var date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));

if (isNaN(date) || date.getMonth() + 1 !== parseInt(month) || date.getDate() !== parseInt(day)) {
  date = null;
}

console.log(date);