0

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

8
  • 1
    PLease add more details, thats a valid date, why would you want null? Commented Jun 8, 2023 at 15:50
  • 3
    new always returns an instance of the class specified, it will never return null. Commented Jun 8, 2023 at 15:52
  • 4
    And Date objects automatically handle overflow of dates. If a day number is higher than the number of days in the specified month, it wraps into the next month. So November 31 is not considered an error, it's just another way of saying December 1. Commented Jun 8, 2023 at 15:53
  • 3
    This is deliberate, it allows you to perform date arithmetic without having to handle crossing between days/months/years yourself. Commented Jun 8, 2023 at 15:54
  • 1
    Compare the year month day of the result with input values. They need to match. Simple. Commented Jun 8, 2023 at 16:00

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.