Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last 3 months names in select dropdown

I have a report where in the user is only allowed to select an option from last 3 months as shown below :

Month requirement in select

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 ?

like image 843
Ashish Bahl Avatar asked Dec 19 '22 07:12

Ashish Bahl


2 Answers

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());
like image 114
VikingCode Avatar answered Dec 24 '22 00:12

VikingCode


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))
like image 21
Gaurav Chaudhary Avatar answered Dec 24 '22 01:12

Gaurav Chaudhary