How to loop through months in Javascript

后端 未结 3 455
温柔的废话
温柔的废话 2021-01-12 15:02

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

var resultList = [];
v         


        
相关标签:
3条回答
  • 2021-01-12 15:09

    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)
    

    0 讨论(0)
  • 2021-01-12 15:14

    Use setMonth() instead of setDate() to sets the month of the date variable.

    date.setMonth(date.getMonth() + 1);
    
    0 讨论(0)
  • 2021-01-12 15:25

    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.

    0 讨论(0)
提交回复
热议问题