英文:
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 = "2023";
var month = "11"
var day = "31"
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 = "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);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论