简体   繁体   中英

How do you loop backwards through the months starting with the current one?

I'm using JavaScript, trying to fill a barchart. The last line on the chart is the current month (November 2014 at the time of writing, or 10 if you use JavaScript's Date().getMonth() method). It starts counting at the next month of the previous year (so December 2013, or 11 if using getMonth()).

My question: what is the most efficient way to loop 12 months through time starting at 11 months before the current time?

My preferred output would be:

  • December 2013
  • January 2014
  • February 2014
  • ...
  • November 2014

You can use a for loop and subtract the month from the current date. Like what is done below:

 var dateObj = new Date(); var dateStrings = []; var dateFormatOptions = { month: 'long', year: 'numeric' }; for (var i = 0; i < 12; ++i) { dateStrings.unshift(dateObj.toLocaleString('en-US', dateFormatOptions)); dateObj.setMonth(dateObj.getMonth() - 1); } document.getElementById("output").innerHTML = dateStrings.join("\\n"); 
 <pre id="output"></pre> 

This code will create an array with the date strings you want.

Possible solution:

var date = new Date();
var dates = [];
var i, len;

for (i = 0, len = 12; i < len; i++) {
    date.setMonth(date.getMonth() - 1);

    dates.unshift(date.toLocaleString('en-us', {
        month: 'long',
        year: 'numeric'
    }));
}

Like this:

 var months = [ "January" , "February" , "March" , "April" , "May" , "June" , "July" , "August" , "September" , "October" , "November" , "December" ]; var now = new Date; var month = now.getMonth() + 1; var year = now.getFullYear() - 1; if (month === 12) { month = 0; year++; } for (var i = 0; i < 12; i++) { console.log(months[month++] + " " + year); if (month === 12) { month = 0; year++; } } 

I would just use a for loop and subtract the year (and set date) when they overflow:

 var date = new Date(); var currentMonth = date.getMonth(); var currentYear = date.getFullYear(); console.log(currentYear) var month = ["January","February","March","April","May","June","July", "August","September","October","November","December"]; var myArray = []; for(var i = 0; i < 12; i++){ if(currentMonth == - 1){ currentMonth = 11; date.setFullYear(parseInt(currentYear) - 1); currentYear = date.getFullYear(); } myArray.push(month[currentMonth]+" "+currentYear); currentMonth--; } alert(myArray); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM