Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get date string from day number and month number using moment?

dayNumber: 28,
monthNumber: 2,

expected output using moment "2022-02-28"

What I’ve tried const date = moment() .month(monthNumber) .days(dayNumber) .format("YYYY-MM-DD");

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but that gives me something like "2022-03-17"

what am I doing wrong?

>Solution :

You have two errors in your code:

  • The first one is that you need to replace the days function call with date
  • The second one is that the argument of the month function starts from 0. So 0 is January, 1 is February etc.

So, what you need to do in order to get 2022-02-28 is the following:

const date = moment() .month(1) .date(28) .format("YYYY-MM-DD");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading