Hello friends, In this post you will find a javascript code that helps you to get last 3 months name with current year using javascript function. This is really helpful for those also who are working in lightning component or lightning web component.
Get last 3 months name in javascript
Here, I am writing two types of function, first one print fullyear and second print last 2 digits of year.
1.) With full year:
function getLast3MonthsWithFullYear() {
var monthNames = ["", "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
var months = new Array();
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
var i = 0;
do {
months.push(monthNames[parseInt((month > 9 ? "" : "0") + month)] + "-" + year);
if (month == 1) {
month = 12;
year--;
} else {
month--;
}
i++;
} while (i < 3);
return months;
}
document.write(getLast3MonthsWithFullYear());
Output:
2.) With last 2 digits of year:function getLast3MonthsWith2DigitYear() {
var monthNames = ["", "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
var months = new Array();
var today = new Date();
var year = today.getFullYear().toString().slice(-2);
var month = today.getMonth();
var i = 0;
do {
months.push(monthNames[parseInt((month > 9 ? "" : "0") + month)] + "-" + year);
if (month == 1) {
month = 12;
year--;
} else {
month--;
}
i++;
} while (i < 3);
return months;
}
document.write(getLast3MonthsWith2DigitYear());
Output:
Thank you.
0 Comments
Post a Comment