Skip to content
Advertisement

JavaScript error with formatting Date objects

I am receiving a very specific logic error in my code and I am not sure what is causing it. I have a function formatDate() which gets the current date and puts it in the format yyyy-mm-dd. To achieve this, I have to add a “0” to the front of the month or day when it is a single digit (smaller than 10).

I have written this code to do this:

let year = currentDate.getFullYear();
let month = currentDate.getMonth() < 10 ? "0" + (currentDate.getMonth() + 1) : currentDate.getMonth() + 1;
let date = currentDate.getDate() < 10 ? "0" + currentDate.getDate() : currentDate.getDate();

However, when I do console.log(year + "-" + month + "-" + date), I get this:

2020-010-24

As you can see, the zero is not added to the date but it is added to the month, despite both variables having the exact same logic. I have no idea what is causing this.

Advertisement

Answer

currentDate.getMonth() returns 9, this mean your condition currentDate.getMonth() < 10 became true, then it appends “0” to month variable.

Get “correct” month value then make the condition:

let month = (currentDate.getMonth() + 1) < 10 ? "0" + (currentDate.getMonth() + 1) : currentDate.getMonth() + 1;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement