-1

I wish to have all the days from the current month in an array. For example this month (April 2022) has 30 days so I wish to have an array of integers like so:

const monthDays = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 , 30 ]

My attempt :

Array.from(Array(moment('2022-04').daysInMonth()).keys())

And the output is :

//  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

I have and idea how moment works and 0 is always the first day or the first month , but how can i achieve the result that i want from the example above

So basically moment will generate automatically this array if I fetch the current month. How can we achieve that?

PandaMastr
  • 687
  • 3
  • 14
  • 35

1 Answers1

1
  1. Create moment object
  2. Set the month to the desired month
  3. Use daysInMonth() to get the number of days
  4. Create an array from 1 to the result of step 3

const mom = new moment();
mom.set('month', 3); // 0-indexed, so 3 --> 4 --> April

const daysInApril = mom.daysInMonth();
const aprilDays   = Array.from({length: daysInApril}, (_, i) => i + 1);

console.log(aprilDays);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
0stone0
  • 34,288
  • 4
  • 39
  • 64