List month name and year for the last 6 months
Asked Answered
S

8

6

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?

Swot answered 8/1, 2015 at 16:7 Comment(2)
In JavaScript months are indexed from 0 to 11Loge
Ok, I get that. If I change to this, I get the most of the names correctly now but December shows as undefined.Swot
L
16

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

Loge answered 8/1, 2015 at 16:18 Comment(0)
P
4

I'll expand a bit on the answer provided by @zynetro to include the year as well.

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

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

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

Here is a fiddle for it.

Pamulapan answered 8/1, 2015 at 16:24 Comment(0)
C
1
 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 {

    if (month < 0) {
        month = 11;
        year--;
    }

    $("#pickWinners_month").append($("<option />").val((month > 9 ? "" : "0") + month + "/01/" + year).html(monthNames[month] + " " + year));

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

Here is a working Sample

Clannish answered 8/1, 2015 at 16:27 Comment(0)
T
1
const today = new Date();
let lastSixMonths = []

for (var i = 6; i > 0; i -= 1) {
    const date = new Date(today.getFullYear(), today.getMonth() - i, 1);
    lastSixMonths.push(moment(date).format("MMMM YYYY"))
}

return lastSixMonths.reverse() // Result
Truancy answered 13/2, 2021 at 14:39 Comment(3)
Your answer is flagged for low quality. If your logic holds perfectly ,can you also give a run through of the code in the answer.Knowling
While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and eventually apply that knowledge to their own code. You are also likely to have positive-feedback/upvotes from users, when the code is explained.Ephedrine
The community encourages adding explanations alongisde code, rather than purely code-based answers (see here).Deil
P
1

here is a optimized way to do it, minimum number of iteration and minimum use of Date() Object

const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',]

    let result = []
    let monthIndex = new Date().getMonth()
    for (let i = 0; i < 6; i++) {
      result.unshift(monthNames[monthIndex]);
      monthIndex ? monthIndex-- : monthIndex = 11
    }
console.log("Result: ",result)
Puglia answered 31/1 at 11:3 Comment(0)
L
0

As zaynetro said, you have wrong month indexes in:

  • monthNames[month]
  • month == 0
  • month = 11

Here is full 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 > 9 ? "" : "0") + month + "/01/" + year).html(monthNames[month] + " " + year));
    if (month == 0) {
        month = 11;
        year--;
    } else {
        month--;
    }

    i++;
} while (i < 6);
Liverpool answered 8/1, 2015 at 16:19 Comment(3)
Cool, that gives me accurate values, but I don't want the current month, so for when today is in January, show July through December of last year.Swot
So just decrease initial value of month by oneLoge
@Loge can you elaborate your answer for "if I do not want the current month"?Charters
S
0

You can do something like this:

$date ='2015-01-01'
for (int i=0;i<6; i++){
    $datemonthBefore = date('Y-m-d',strtotime('-i months', strtotime($date)));
    var month = datemonthBefore.getMonth();
}
Semipermeable answered 8/1, 2015 at 16:24 Comment(0)
S
0

Looks like I got it. Subtract a month from today's date, then use that as the new starting date.

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

var lastMonth = new Date();
lastMonth.setMonth(lastMonth.getMonth() - 1);
var year = lastMonth.getFullYear();
var month = lastMonth.getMonth();

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

    i++;
} while (i < 6);
Swot answered 8/1, 2015 at 17:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.