Wrong date not identified by BTT JavaScript

I tried to use "Run Real JavaScript" in BTT and put the code below.

(async() => {
let year = 2021;
let month = 1;
let day = 40;
let newDate = new Date(year + "/" + month + "/" + day);
let status = newDate instanceof Date && !isNaN(newDate.getTime());
returnToBTT('');
})()

status returns "true" which is wrong because "2021/1/40" is an invalid date, but if I run it in Google Console, it returns "false" which is correct.
What is wrong?

The JavaScript engine of macOS convert this into a valid date:

new Date('2021/1/40');
--> Tue Feb 09 2021 00:00:00 GMT+0100 (CET)

That's strange.
You can check this in the Skripteditor app.

1 Like

Yep, unfortunately especially with invalid dates the various JS engines have all sort of weird behavior ....

That's true. Thanks a lot Dirk and Andreas.

You can check if the date is valid with this:

let year = 2021;
let month = 1;
let day = 40;
let newDate = new Date(year + "/" + month + "/" + day);
let status = newDate instanceof Date && newDate.getFullYear() == year && (newDate.getMonth() + 1) == month && newDate.getDate() == day;

yes, very good idea. Thanks a lot Dirk.