Generate array of times (as strings) for every X minutes in JavaScript

后端 未结 15 1773
耶瑟儿~
耶瑟儿~ 2020-12-24 01:46

I\'m trying to create an array of times (strings, not Date objects) for every X minutes throughout a full 24 hours. For example, for a 5 minute interval the arr

15条回答
  •  青春惊慌失措
    2020-12-24 02:18

    To start list from particular time like 3:00 PM and loop quarterly(every 15 minutes):

    const hours = [];
    const startHour = 15;
    
    for (let hour = 0; hour < 24; hour++) {
      hours.push(
        moment({ hour })
          .add(startHour, 'hours')
          .format('h:mm A')
      );
    
      hours.push(
        moment({
          hour,
          minute: 15
        })
          .add(startHour, 'hours')
          .format('h:mm A')
      );
    
      hours.push(
        moment({
          hour,
          minute: 30
        })
          .add(startHour, 'hours')
          .format('h:mm A')
      );
    
      hours.push(
        moment({
          hour,
          minute: 45
        })
          .add(startHour, 'hours')
          .format('h:mm A')
      );
    }
    

提交回复
热议问题