Rod0n
Rod0n

Reputation: 1079

Generate variable minutes interval

I need to generate a variable number of ranges between a day depending on the number of minutes in order to compare them to a list of files to see if there's a gap in the data.

For example, if the minutes interval is 60*12 (half a day) I'd need to generate the following list:

['00:00_12:00','12:00_00:00']

If the minutes interval is 5:

['00:00_00:05', '00:05_00:10',..................., '23:55_00:00']

I'm trying to use the moment library in order to simplify the task, I guess using

moment(date).add(interval, 'minutes').format('HH:MM');

But I can't come up with the correct loop to get the desired output.

This is my current code but it's not even working:

var interval_1 = 60;
var interval_2 = 5;
var interval_3 = 60*12;
var today = moment.utc(new Date()).startOf('day').toISOString();
console.log(today)
from = moment.utc(new Date()).startOf('day').format('HH:MM')
var to = ''
while (to !== '00:00'){
    to = moment(from).add(interval_1, 'minutes').format('HH:MM');
  console.log(from, '_', to, '.json')
  from = to
}

Upvotes: 0

Views: 320

Answers (1)

Scott Sauyet
Scott Sauyet

Reputation: 50807

I think the formatting you need to do on each hour-minute combination is simple enough that you don't need to pull in a library for it. Here's how I might do this:

const formatMinutes = (m) =>
  String (((m - (m % 60)) / 60 % 24)) .padStart (2, '0') + 
  ':' + 
  String (m % 60) .padStart (2, '0')

const divideDay = (n) => 
  Array .from (
    {length: 24 * 60 / n}, 
    (_, i) => [i * n, (i + 1) * n]
  ).map (([b, e]) => `${formatMinutes (b)}_${formatMinutes (e)}`)


const testCases = [327, 60, 5, 60 * 12]

testCases .forEach (
  minutes => console .log (`${minutes} minutes: ["${divideDay (minutes) .join('", "')}"]\n`)
)
.as-console-wrapper {max-height: 100% !important; top: 0}

formatMinutes takes a number of minutes and formats it in hh:mm format, left-padding each component with 0 if needed. The main function is divideDay, which breaks down the minutes into [[0, 5], [5, 10], ... [1435, 1440]] arrays and then maps these begin-end pairs into a formatted string by calling formatMinutes on each one.

If you want to deal with possible partials -- if for instance you pass 327 as the number of minutes -- by capturing the remaining minute into a final section, you could change it a bit like this:

const divideDay = (n) => 
  Array .from (
    {length: Math .ceil (24 * 60 / n)}, 
    (_, i) => [i * n, Math .min ((i + 1) * n, 24 * 60)]
  ).map (([b, e]) => `${formatMinutes (b)}_${formatMinutes (e)}`)

and then

divideDay (327) //=> ['00:00_05:27', '05:27_10:54', '10:54_16:21', '16:21_21:48']

Upvotes: 1

Related Questions