Date object’s behaviour when using “yyyy-mm-dd” but omitting the “dd”

If you create Date object like this: new Date(‘1980-01-01’); you will get a valid date although if you try to give a string to the constructor like new Date(‘1980-01’) then it can be valid like the previous Date object.

How could this be?

The omitted day will be set as default ’01’ and your object will be Date(‘1980-01-01’); besides you only set ‘1980-01′. If you wrap this into a funcion that checks let’s say all your input fields’ values (let’s assume 1 input for day another one for month and the last one for year) then you can always check if these inputs are empty or not and if the day is an empty string then you can set it as NULL then you won’t get the day added as default ’01’ by the Date object’s constructor.

It will be new Date(‘1980-01-null’); and the result is an invalid Date object as expected.  Always encourage unit tests and you can easily avoid traps like the one above.

The gist can be found here: https://gist.github.com/joshycube/2a35aa15ebdd34f0f45368750acf7d69

 

Leave a Reply