最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

date - Result of getting next 12 months in Javascript is messed up - Stack Overflow

programmeradmin2浏览0评论

I have the following code for generating a list of the next 12 months (inclusive), starting from today's date:

function DateUtilFunctions() {
    var self = this;

    var monthNames = new Array();

    monthNames[0] = "January";
    monthNames[1] = "February";
    monthNames[2] = "March";
    monthNames[3] = "April";
    monthNames[4] = "May";
    monthNames[5] = "June";
    monthNames[6] = "July";
    monthNames[7] = "August";
    monthNames[8] = "September";
    monthNames[9] = "October";
    monthNames[10] = "November";
    monthNames[11] = "December";

    self.getNext12MonthNamesWithYear = function () {
        var months = new Array();
        var today = new Date(Date());

        var loopDate = new Date();
        loopDate.setTime(today.valueOf());

        var todayPlus12Months = new Date(today.setMonth(today.getMonth() + 12));

        while (loopDate.valueOf() < todayPlus12Months.valueOf()) {
            alert(loopDate);
            alert(loopDate.getMonth());
            var month = monthNames[loopDate.getMonth()];


            months.push(month + ' ' + loopDate.getFullYear());
            loopDate.setMonth(loopDate.getMonth() + 1);
        }

        return months;
    };
}

The result of calling getNext12MonthNamesWithYear() is:

  • "May 2012"
  • "July 2012"
  • "August 2012"
  • "May 2012"
  • "July 2012"
  • "August 2012"
  • "September 2012"
  • "October 2012"
  • "November 2012"
  • "December 2012"
  • "January 2013"
  • "February 2013"
  • "March 2013"
  • "April 2013"
  • "May 2013"

As you can, the start of the list is a bit weird, in that "June" is missing, plus "May", "July" and "August" appear twice.

Naturally I;m doing something very wrong here; could someone please help me out?

EDIT:

Based on micadelli's comment, here is the solution I used:

function DateUtilFunctions() {
    var self = this;

    var monthNames = new Array();

    monthNames[0] = "January";
    monthNames[1] = "February";
    monthNames[2] = "March";
    monthNames[3] = "April";
    monthNames[4] = "May";
    monthNames[5] = "June";
    monthNames[6] = "July";
    monthNames[7] = "August";
    monthNames[8] = "September";
    monthNames[9] = "October";
    monthNames[10] = "November";
    monthNames[11] = "December";

    self.getNext12MonthNamesWithYear = function () {
        var months = new Array();
        var today = new Date();
        var tmpDate = new Date();
        var tmpYear = tmpDate.getFullYear();
        var tmpMonth = tmpDate.getMonth();
        var monthLiteral;

        for (var i = 0; i < 12; i++) {
            tmpDate.setMonth(tmpMonth + i);
            tmpDate.setFullYear(tmpYear);
            monthLiteral = monthNames[tmpMonth];

            months.push(monthLiteral + ' ' + tmpYear);

            tmpYear = (tmpMonth == 11) ? tmpYear + 1 : tmpYear;
            tmpMonth = (tmpMonth == 11) ? 0 : tmpMonth + 1;
        }

        return months;
    };
}

I have the following code for generating a list of the next 12 months (inclusive), starting from today's date:

function DateUtilFunctions() {
    var self = this;

    var monthNames = new Array();

    monthNames[0] = "January";
    monthNames[1] = "February";
    monthNames[2] = "March";
    monthNames[3] = "April";
    monthNames[4] = "May";
    monthNames[5] = "June";
    monthNames[6] = "July";
    monthNames[7] = "August";
    monthNames[8] = "September";
    monthNames[9] = "October";
    monthNames[10] = "November";
    monthNames[11] = "December";

    self.getNext12MonthNamesWithYear = function () {
        var months = new Array();
        var today = new Date(Date());

        var loopDate = new Date();
        loopDate.setTime(today.valueOf());

        var todayPlus12Months = new Date(today.setMonth(today.getMonth() + 12));

        while (loopDate.valueOf() < todayPlus12Months.valueOf()) {
            alert(loopDate);
            alert(loopDate.getMonth());
            var month = monthNames[loopDate.getMonth()];


            months.push(month + ' ' + loopDate.getFullYear());
            loopDate.setMonth(loopDate.getMonth() + 1);
        }

        return months;
    };
}

The result of calling getNext12MonthNamesWithYear() is:

  • "May 2012"
  • "July 2012"
  • "August 2012"
  • "May 2012"
  • "July 2012"
  • "August 2012"
  • "September 2012"
  • "October 2012"
  • "November 2012"
  • "December 2012"
  • "January 2013"
  • "February 2013"
  • "March 2013"
  • "April 2013"
  • "May 2013"

As you can, the start of the list is a bit weird, in that "June" is missing, plus "May", "July" and "August" appear twice.

Naturally I;m doing something very wrong here; could someone please help me out?

EDIT:

Based on micadelli's comment, here is the solution I used:

function DateUtilFunctions() {
    var self = this;

    var monthNames = new Array();

    monthNames[0] = "January";
    monthNames[1] = "February";
    monthNames[2] = "March";
    monthNames[3] = "April";
    monthNames[4] = "May";
    monthNames[5] = "June";
    monthNames[6] = "July";
    monthNames[7] = "August";
    monthNames[8] = "September";
    monthNames[9] = "October";
    monthNames[10] = "November";
    monthNames[11] = "December";

    self.getNext12MonthNamesWithYear = function () {
        var months = new Array();
        var today = new Date();
        var tmpDate = new Date();
        var tmpYear = tmpDate.getFullYear();
        var tmpMonth = tmpDate.getMonth();
        var monthLiteral;

        for (var i = 0; i < 12; i++) {
            tmpDate.setMonth(tmpMonth + i);
            tmpDate.setFullYear(tmpYear);
            monthLiteral = monthNames[tmpMonth];

            months.push(monthLiteral + ' ' + tmpYear);

            tmpYear = (tmpMonth == 11) ? tmpYear + 1 : tmpYear;
            tmpMonth = (tmpMonth == 11) ? 0 : tmpMonth + 1;
        }

        return months;
    };
}
Share Improve this question edited May 31, 2012 at 12:29 Jason Evans asked May 31, 2012 at 10:53 Jason EvansJason Evans 29.2k15 gold badges93 silver badges156 bronze badges 2
  • Use a library like momentjs – Esailija Commented May 31, 2012 at 12:19
  • Thanks for suggesting 'moment.js'. Although I have used a different approach, I will keep that js on my tools list. – Jason Evans Commented May 31, 2012 at 12:22
Add a comment  | 

5 Answers 5

Reset to default 12

Don't try to manipulate the Date object - just use it to get the initial values for month and year and then use simple arithmetic on the results:

function getNext12MonthNamesWithYear() {
    var now = new Date();
    var month = now.getMonth();
    var year = now.getFullYear();

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

    var res = [];
    for (var i = 0; i < 13; ++i) {
        res.push(names[month] + ' ' + year);
        if (++month === 12) {
            month = 0;
            ++year;
        }
    }
    return res;
}

working demo at http://jsfiddle.net/alnitak/SQQdg/

Here is my solution using Moment.js

Next 12 Months

let months = [];
let monthsRequired = 12

for (let i = 1; i <= monthsRequired; i++) {
  months.push( moment().add(i, 'months').format('MMMM YYYY') )
}

console.log(months)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Just in case if you need previous 12 Months

let months = [];
let monthsRequired = 12

for (let i = monthsRequired; i >= 1; i--) {
  months.push( moment().subtract(i, 'months').format('MMMM YYYY') )
}

console.log(months)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

I dont see any reason why this wouldn't work

function DateUtilFunctions() {
   var self = this;

   var monthNames = new Array();

   monthNames[0] = "January";
   monthNames[1] = "February";
   monthNames[2] = "March";
   monthNames[3] = "April";
   monthNames[4] = "May";
   monthNames[5] = "June";
   monthNames[6] = "July";
   monthNames[7] = "August";
   monthNames[8] = "September";
   monthNames[9] = "October";
   monthNames[10] = "November";
   monthNames[11] = "December";

   self.getNext12MonthNamesWithYear = function () {
     var months = new Array();
     var today = new Date();
     var tmpDate = new Date();
     var tmpYear = tmpDate.getFullYear();
     var tmpMonth = tmpDate.getMonth();
     var monthLiteral;

     for (var i = 0 ; i < 12 ; i++) {
        tmpDate.setMonth(tmpMonth + i);
        tmpDate.setFullYear(tmpYear);
        monthLiteral = monthNames[tmpMonth];
        months.push(monthLiteral + ' ' + tmpYear);
        tmpMonth = (tmpMonth == 11) ? 0 : tmpMonth+1;
        tmpYear = (tmpMonth == 11) ? tmpYear+1 : tmpYear;
     }

     return months;
   };
}

JS Bin
http://jsbin.com/aqezom

Here is a working version. You can not perform setMonth directly if the value is more than 12. Also, there is no 31st for some of the months which results in unexpected results. JS fiddle here FIDDLE

    var monthNames = new Array();

    monthNames[0] = "January";
    monthNames[1] = "February";
    monthNames[2] = "March";
    monthNames[3] = "April";
    monthNames[4] = "May";
    monthNames[5] = "June";
    monthNames[6] = "July";
    monthNames[7] = "August";
    monthNames[8] = "September";
    monthNames[9] = "October";
    monthNames[10] = "November";
    monthNames[11] = "December";

var today = new Date();
var currentMonth = today.getMonth();
var i;
for (i = 0 ; i < 12 ; i++) {
    var newMonth = currentMonth + i;
    var newYear = newMonth > 11 ? today.getFullYear() + 1: today.getFullYear();
    newMonth = newMonth > 11? (newMonth - 12): newMonth;

    var newDate = new Date(newYear, newMonth, '1');

    console.log(monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());
}

​

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;
    }
}
发布评论

评论列表(0)

  1. 暂无评论