Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List month name and year for the last 6 months

I had this working fine for the middle of the year but now that we've rolled over to a new year, my code breaks. I need to get the month name and year for the previous 6 months.

My modified code:

var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();

var i = 0;
do {
    $("#pickWinners_month").append($("<option />").val((month > 8 ? "" : "0") + month + "/01/" + year).html(monthNames[month - 1] + " " + year));
    if (month == 0) {
        month = 11;
        year--;
    } else {
        month--;
    }

    i++;
} while (i < 6);

Can someone give me a hand with this?

like image 440
Connie DeCinko Avatar asked Dec 01 '22 18:12

Connie DeCinko


1 Answers

You could do something like this

var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var today = new Date();
var d;
var month;

for(var i = 6; i > 0; i -= 1) {
  d = new Date(today.getFullYear(), today.getMonth() - i, 1);
  month = monthNames[d.getMonth()];
  console.log(month);
}

Run code

like image 97
zaynetro Avatar answered Dec 10 '22 12:12

zaynetro