3

I'm using moment.js and would like to create an array that contains all of the times in 15 minute intervals from the current time. So for example:

Current time is 1:35pm. The next time would be 1:45pm, then 2:00, 2:15, 2:30, 2:45, etc. up until a certain point.

I'm really not sure how to this. Would anyone be able to point me in the right direction?

dertkw
  • 7,798
  • 5
  • 37
  • 45
dzm
  • 22,844
  • 47
  • 146
  • 226

2 Answers2

7

Try this:

function calculate(endTime) {
    var timeStops = [];
    var startTime = moment().add('m', 15 - moment().minute() % 15);

    while(startTime <= endTime){
        timeStops.push(new moment(startTime));
        startTime.add('m', 15);
    }

    return timeStops;
}

usage:

calculate(moment().add('h', 1));

This will return time intervals of every quarter of hour (like you said) h:15, h:30, h:45, h+1:00... It also contains seconds, so you might set seconds to 0, since I was not sure if you need them or not.

You also can see working example on FIDDLE

Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
  • Note, since time of writing moment API has changed so that the unit of time is specified after the amount. startTime.add(15, m); – nclord Aug 30 '16 at 10:23
1

I'm not as familiar with momentjs but this is relatively easy to do in pure Javascript. To get the closest 15 minutes you can use this solution here. Then if you put that in a date variable you can just add 15 minutes as many times as you want! So the resulting Javascript is:

var d = new Date();
var result = "";
for (var idx = 0; idx < 3; idx++)
{
    var m = (((d.getMinutes() + 7.5)/15 | 0) * 15) % 60;
    var h = ((((d.getMinutes()/105) + .5) | 0) + d.getHours()) % 24;
    d = new Date(d.getYear(), d.getMonth(), d.getDay(), h, m, 0, 0);

    if (idx > 0) result += ", ";
    result += ("0" + h).slice(-2) + ":" + ("0" + m).slice(-2);

    d = addMinutes(d, 15);
}

SEE THIS IN A FIDDLE

Notes - I just added 15 minutes 3 times arbitrarily. You could calculate the difference between the time you want and now if you need a different number of intervals. Also note that I don't know exactly what this would do if it is almost midnight, though that would be easy enough to test and code around.

Best of luck!

Community
  • 1
  • 1
drew_w
  • 10,320
  • 4
  • 28
  • 49