Using Moment.js I would like to get all days in a month of specific year in an array. For example:
January-2014:
[
\"01-wed\",
\"02-thr\",
\"03-fri\",
\"04-s
Alternatively you might now use moment range to achieve this :
const month = moment('2012-02', 'YYYY-MM');
const range = moment().range(moment(month).startOf('month'), moment(month).endOf('month'));
const days = range.by('days');
console.log([...days].map(date => date.format('DD-ffffd')));
To get days in a month with moment.js i use this one :
function daysInMonth(month) {
var count = moment().month(month).daysInMonth();
var days = [];
for (var i = 1; i < count+1; i++) {
days.push(moment().month(month).date(i));
}
return days;
}
Then to call the function
var days = daysInMonth( moment().month() );
Alternative with momentjs, working for me
function getDaysArrayByMonth() {
var daysInMonth = moment().daysInMonth();
var arrDays = [];
while(daysInMonth) {
var current = moment().date(daysInMonth);
arrDays.push(current);
daysInMonth--;
}
return arrDays;
}
And you can check
var schedule = getDaysArrayByMonth();
schedule.forEach(function(item) {
console.log(item.format("DD/MM"));
});
you can do it using for loop with moment
var daysInMonth = [];
var monthDate = moment().startOf('month');
for(let i=0;i<monthDate.daysInMonth();i++){
let newDay=monthDate.clone().add(i,'days');
daysInMonth.push(newDay.format('DD-ffffd'));
}
console.log(daysInMonth)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
You could use _.times
helper from lodash
alongside moment like so:
var daysInMonth = [];
var monthDate = moment().startOf('month'); // change to a date in the month of interest
_.times(monthDate.daysInMonth(), function (n) {
daysInMonth.push(monthDate.format('DD-ffffd')); // your format
monthDate.add(1, 'day');
});
console.log(daysInMonth)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>