How to create a for loop which returns an array of new date objects for remaining days in a month using javascript

后端 未结 1 1552
半阙折子戏
半阙折子戏 2021-01-26 11:13

I need to return an array containing a Date object for each day remaining in the month, for a given Date.

I need a for loop that creates new Date()

相关标签:
1条回答
  • 2021-01-26 11:58

    You can use the getTime and setTime methods of the Date object to advance one day at a time.

    var days = [];
    var now = new Date();
    var day = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
    while (day.getMonth() === now.getMonth()) {
      days.push(day);
    
      // Go to the next day
      day = new Date(day.getTime() + 86400000);  // There are 86400000 milliseconds in a day
    }
    
    0 讨论(0)
提交回复
热议问题