I am trying to show current month and all previous months using moment.js in javascript, How to write code using moment.js?
Asked
Active
Viewed 195 times
-2
-
Have a look at :https://stackoverflow.com/a/29303336/7124761 – Prashant Pimpale Jul 17 '18 at 11:59
-
Have a look at my ans to use the months initialized by `moment.js`. – Vignesh Raja Jul 17 '18 at 12:19
4 Answers
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
-
-
This gets only current and previous month. Need all previous months as requested by OP. – Vignesh Raja Jul 17 '18 at 12:52
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