Loop through a date range with JavaScript

后端 未结 10 781
情话喂你
情话喂你 2020-11-30 17:46

Given two Date() objects, where one is less than the other, how do I loop every day between the dates?

for(loopDate = startDate; loopDate < e         


        
10条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 18:45

    I think I found an even simpler answer, if you allow yourself to use Moment.js:

    // cycle through last five days, today included
    // you could also cycle through any dates you want, mostly for
    // making this snippet not time aware
    const currentMoment = moment().subtract(4, 'days');
    const endMoment = moment().add(1, 'days');
    while (currentMoment.isBefore(endMoment, 'day')) {
      console.log(`Loop at ${currentMoment.format('YYYY-MM-DD')}`);
      currentMoment.add(1, 'days');
    }

提交回复
热议问题