Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last 12 months in Javascript

I got an Kendo ui Chart like this one and have to show the last 12 months of todays date on the axis.
I found this to extend the date object to get the previous month. The problem seems to be when I got an Date like "2013/05/31" and the previous months got no 31st day.

Date.prototype.toPrevMonth = function (num) {
    var thisMonth = this.getMonth();
    this.setMonth(thisMonth-1);
    if(this.getMonth() != thisMonth-1 && (this.getMonth() != 11 || (thisMonth == 11 &&      this.getDate() == 1)))
    this.setDate(0);
}


new Date().toPrevMonth(11),
new Date().toPrevMonth(10),
new Date().toPrevMonth(9),
new Date().toPrevMonth(8),
new Date().toPrevMonth(7),
new Date().toPrevMonth(6),
new Date().toPrevMonth(5),
new Date().toPrevMonth(4),
new Date().toPrevMonth(3),
new Date().toPrevMonth(2),
new Date().toPrevMonth(1),
new Date().toPrevMonth(0)

Can anyone help me out with the if state?
The function is build to show only the previous month, but I need the last 12 previous months.

Or is there a much easier solution? :-)

Thanks for all!

like image 771
chris Avatar asked Sep 26 '13 06:09

chris


People also ask

What is getMonth in JavaScript?

getMonth() The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).

How do I calculate the date in JavaScript three months prior to today?

First select the date object. Then use the getMonth() method to get the months. Then subtract three months from the getMonth() method and return the date.

How do I find the last date of the month?

To find the last date of the month, we will use the inbuilt function of Excel called the EOMONTH. This function will help us to return the last date of the month.


2 Answers

Including year of month

var monthName = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var d = new Date();
d.setDate(1);
for (i=0; i<=11; i++) {
    console.log(monthName[d.getMonth()] + ' ' + d.getFullYear());
    d.setMonth(d.getMonth() - 1);
}
like image 76
jlizanab Avatar answered Sep 23 '22 00:09

jlizanab


I also needed a list of the last 12 months this is what I did:

var theMonths = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var today = new Date();
var aMonth = today.getMonth();
var i;
for (i=0; i<12; i++) {
    document.writeln(theMonths[aMonth] + '<br>'); //here you can do whatever you want...
    aMonth++;
    if (aMonth > 11) {
        aMonth = 0;
    }
}
like image 32
elad silver Avatar answered Sep 22 '22 00:09

elad silver