I have a report where in the user is only allowed to select an option from last 3 months as shown below :
I want to write a javaScript function to achieve this.
What I tried was :
function getLastMonths(n) {
var months = new Array();
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var i = 0;
do {
months.push(year + (month > 9 ? "" : "0") + month);
if(month == 1) {
month = 12;
year--;
} else {
month--;
}
i++;
} while(i < n);
return months;
}
Then I called the function by passing parameters :
document.write(getLastMonths(4));
It prints :
201704,201703,201702,201701
Which is not the pattern I require it in.
Can anyone help me out here ?
Take a look here. It's a bit shorter thanks to for loop
function getLast3Months() {
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var today = new Date();
var last3Months = []
for (i = 0; i < 3; i++) {
last3Months.push(monthNames[(today.getMonth() - i)] + ' - ' +today.getFullYear() );
}
return last3Months;
}
document.write(getLast3Months());
You can do it like this. Simply go on subtracting one month
from current date
function getLastMonths(n) {
var m =['January','February','March','April','May','June','July','August','September','October','November','December'];
var last_n_months =[]
var d = new Date()
for(var i=0;i<n;i++){
last_n_months[i] = m[d.getMonth()]+ ' - ' + d.getFullYear().toString()
d.setMonth(d.getMonth()-1)
}
return last_n_months
}
console.log(getLastMonths(3))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With