Search code examples
momentjsdate-range

Foreach hours in momentJs


I'm using moment in my app. I want to iterate through time from 00:00 to 23:00, adding to time 30 minutes, I'm trying like this:

var tStart = moment('2020-05-14 01:00:00', 'm-d-Y H:i');
var tEnd = moment('2020-05-14 23:00:00', 'm-d-Y H:i');

for (var t = tStart; t.isBefore(tEnd); t.add(30, 'minutes')) {
    console.log(t.format("LTS"));
}

But output is:

01:20:00
02:05:00
02:50:00
03:35:00
04:20:00
(...)
23:05:00

My question is, why it starts from 01:20:00 while I set variable to 01:00:00?


Solution

  • Try changing moment constructor with the proper format.

    See the following snippet:

    var tStart = moment("2020-05-14 01:00:00", "YYYY-MM-DD hh:mmss");
    var tEnd = moment("2020-05-14 23:00:00", "YYYY-MM-DD hh:mm:ss");
    for (var t = moment(tStart); t.isBefore(tEnd); t.add(30, "minutes")) {
      console.log(t.format("LTS"));
    }
    <script src="https://momentjs.com/downloads/moment.js"></script>