0

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.

4
  • Side note: You might consider: let month = String(currentDate.getMonth() + 1).padStart(2, "0"); Commented Oct 24, 2020 at 12:13
  • Just out of curiosity, is there a reason you can't use a standard function like developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… for this and then modify it, rather than writing the whole thing from scratch? Commented Oct 24, 2020 at 12:18
  • Side note 2: getMonth and 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 use current.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). Commented Oct 24, 2020 at 12:19
  • I strongly recommend to use dayjs to format the date. Commented Oct 24, 2020 at 12:32

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.