简体   繁体   中英

How to loop through months in Javascript

I'm trying to generate a list of string dates in months (ie ["Oct 2014", "Nov 2014",... "Jan 2015" ]) using the code here:

var resultList = [];
var date = new Date("October 13, 2014");
var endDate = new Date("January 13, 2015");
var monthNameList = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

while (date <= endDate)
{
    var stringDate = monthNameList[date.getMonth()] + " " + date.getFullYear();
    resultList.push(stringDate);
    date.setDate(date.getMonth() + 1);
}

return resultList;

But when I run the code, the screen was frozen (like it was endless loop or something). I never have this problem when I generate daily date (ie date.getDate() +1 ). Am I missing something here?

使用setMonth()而不是setDate()来设置日期变量的月份。

date.setMonth(date.getMonth() + 1);

The problem is within your date.setDate(date.getMonth() + 1) code as the MDN documentation states the setDate function sets the day to the specified Date object. Therefore, it's not behaving as you had intended.

To better illustrate the problem, the date variable is initialized as Mon Oct 13 2014 00:00:00 GMT-0400 (Eastern Daylight Time) . When you call date.getMonth() it returns 9 indicating the 10th month in the calendar year; so incrementing the value by 1 results in setting the day of the date variable to 10 .

On the next iteration, the month hasn't changed, so the code re-executes date.getMonth() which returns 9 again, so on and so on. This unexpected behavior continues to repeat endlessly as the while condition is never satisfied.

The code should be updated to use setMonth instead.

Lets do it using Moment :

moment(sd).add(1,'month').format("MMM-YY")

在此输入图像描述

You can find a difference between two dates

moment("08-31-2017").diff(moment("01-31-2017"), 'months', true)

在此输入图像描述

Please DO NOT just add the month by 1!

It may break in some situations because each month has different days.

The more secure way is like following:

date.setDate(1);
date.setMonth(date.getMonth() + 1);

You may ask why do we have to do date.setDate(1); ? It is because there are different days in each month. If today is Oct 31 and you add the month by 1, then it will become Nov 31. However, Nov 31 is not a valid date...

Here is a rainy example for how it will break in this situation:

const date = new Date(2022, 9, 31); // Oct 31st
date.setMonth(date.getMonth() + 1);
console.log(date); // It returns "Dec 1st"

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