I am trying to use moment to get the previous six months, using the below code.
ngOnInit(){
let mom: moment.Moment;
var d = new Date();
let numberOfMonths=6;
let previousSIxMonths:string[]=[];
while (this.numberOfMonths > 0) {
this.previousSixMonths.push(mom.subtract(this.numberOfMonths, 'months').format('MMMM'));
this.numberOfMonths--;
console.log(this.numberOfMonths);
}
console.log(this.previousSixMonths);
}
However these cards should be displayed whenever I am on the page, and hence I have written the above code inside OnInit. Once I have all the past six months in the array, the idea is to loop over the array and display in cards. But the doesn't really work for me.
I want all my previous six months to be in an array so that I could loop across the array.
Considering this is October month, the expected output should be:
["Oct","Sept","Aug","July","June","May"]
Here is a quick way to do what you're needing:
var previousSixMonths = function(){
let n = 0;
let arRet = [];
for(; n < 6; n++)
arRet.push(moment().subtract(n, 'months').format('MMMM'));
return(arRet)
}();
console.log(previousSixMonths);