javascriptdate-parsing

Return null if incorrect date


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

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

// Log to console
console.log(date)

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


Solution

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

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