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");
but that gives me something like "2022-03-17"
what am I doing wrong?
CodePudding user response:
You have two errors in your code:
- The first one is that you need to replace the
days
function call withdate
- 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");
CodePudding user response:
.month
expects values from 0-11. See: https://momentjs.com/docs/#/get-set/month/
.days
is day of week, .date
is day of month. See: https://momentjs.com/docs/#/get-set/day/ and https://momentjs.com/docs/#/get-set/date/
const date = moment().month(monthNumber-1).date(dayNumber).format("YYYY-MM-DD");
CodePudding user response:
You can also create a moment instance with an array of numbers that mirror the parameters passed to new Date(), e.g. [year, month, day].
NB: Month is zero-indexed.
const year = 2022;
const monthNumber = 2;
const dayNumber = 28;
console.log(moment([year, monthNumber - 1, dayNumber]).format('YYYY-MM-DD'))
<script src="https://momentjs.com/downloads/moment.js"></script>