返回null如果日期不正确。

huangapple go评论57阅读模式
英文:

Return null if incorrect date

问题

我有许多变量 - 年份,月份,日期。我试图将其转换为正确的日期格式。如果变量形成不正确的日期,我想要得到空值。

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这样的日期,它们不是有效的日期。

英文:

I have many variables - year, month, day. I am trying to convert it to correct date form. I would like to get null if variables form incorrect date

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

// Log to console
console.log(date)

<!-- end snippet -->

This code returns 1 December of 2023. But I would like to get null value. How do I do it?

Edit
I edited my code. I have dates like 30/11, 29/02, 31/04 which are not valid dates

答案1

得分: 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);

(请注意,代码部分未进行翻译。)

英文:

You can add a condition to check if the date is valid/not

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var year = &quot;2023&quot;;
var month = &quot;5&quot;;
var day = &quot;32&quot;;

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);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月8日 23:49:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定