ecorvo ecorvo - 8 months ago 147
Javascript Question

How to get list of days in a month with Moment.js

Using Moment.js I would like to get all days in a month of specific year in an array. For example:


any suggestions? I looked through Moment.js docs but couldn't find anything. The closet I got was this:

moment("2012-02", "YYYY-MM").daysInMonth()

But this only return an int with total days for specific month not an array with each day.


Here's a function that will do the trick (not using Moment, but just vanilla JavaScript):

var getDaysArray = function(year, month) {
  var names = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
  var date = new Date(year, month-1, 1);
  var result = [];
  while (date.getMonth() == month-1) {
  return result;

For example:

js> getDaysArray(2012,2)
["1-wed", "2-thu", "3-fri", "4-sat", "5-sun", "6-mon", "7-tue",
 "8-wed", "9-thu", "10-fri", "11-sat", "12-sun", "13-mon", "14-tue",
"15-wed", "16-thu", "17-fri", "18-sat", "19-sun", "20-mon", "21-tue", 
"22-wed", "23-thu", "24-fri", "25-sat", "26-sun", "27-mon", "28-tue",