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.
let month = String(currentDate.getMonth() + 1).padStart(2, "0");getMonthand such on JavaScript dates aren't just simple accessors, they have to do work to go from the underlying milliseconds-since-the-Epoch value to a local timezone month value. Usually it doesn't matter, but if you're giong to usecurrent.getMonth()in three different places anyway, calling it once and reusing the result could simplify things (and avoid the error that hoangdv points out below).dayjsto format the date.