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:

JavaScript

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

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement