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!
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).
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.
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.
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);
}
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;
}
}
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