-2

I am trying to show current month and all previous months using moment.js in javascript, How to write code using moment.js?

jsBee
  • 413
  • 3
  • 13
Rupali
  • 51
  • 9

4 Answers4

2

There you go. :)

var i = parseInt(moment().format('MM')) - 1;
while(i >= 0) {
 console.log(moment().subtract(i--, 'months').format('MMMM'));
}
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
1

you can do that with plain javascript too, no need of any extra library (moment)

var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var todaysDate = new Date();
var currentMonth = months[todaysDate.getMonth()];
console.log('Current month ' + currentMonth);
console.log('Previous month(s) ');
for(let i = months.indexOf(currentMonth) - 1; i >= 0; i--){
    console.log(months[i]);
}
manish
  • 1,450
  • 8
  • 13
  • This code showing me only current month , not previous monthsThis is the Result: "Current month Jul" "Previous month(s) " – Rupali Jul 17 '18 at 12:09
  • @Rupali edited added `months.indexOf(currentMonth)` instead of `currentMonth - 1` in for loop initialization, Thanks :) – manish Jul 17 '18 at 12:12
1

From moment.js, moment.months() and moment.monthsShort() can be used.

var currentmonth = new Date().getMonth();
console.log(moment.months().slice(0,currentmonth+1))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Vignesh Raja
  • 7,927
  • 1
  • 33
  • 42
0

You can simply get this by using moment.js library

document.write(moment().month());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>

You'll get the answer 6 instead of 7 as this is July but this is not wrong as it's written in momentjs documentation that the months are zero indexed so if you want to print 7 you should write it as

document.write(moment().month()+1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>

For more answers you should follow this link https://momentjs.com/docs/#/get-set/month/

Aisha Rafique
  • 53
  • 2
  • 9