Home > OS >  How to return epoch of all midnights in given time span?
How to return epoch of all midnights in given time span?

Time:02-17

I have a time span between two epoch times (in seconds). I want a function that returns the epoch times (in seconds) of all midnights within that time span.

In pseudocode I would want something like this:

const epoch_start = 1600000;
const epoch_end = 16040000;

function getMidnights(start, end){
    // do your magic    
}

console.log(getMidnights(epoch_start, epoch_end));

I would expect the return of that function to look like this: [1600020, 1600400] (these are just example values).

What would be the most efficient way to do this?

My ideas were: get unique list of days within range and return their midnight.

CodePudding user response:

You might step by day rounding by day:

const epoch_start = 1600000000;
const epoch_end   = 1600400000;
const day = 86400;

function getMidnights(start, end){
    midnites = [];
    while (start < end) {
      midnites.push((start/day   .5|0)*day);
      start  = day;
    }
    return midnites;
}

console.log(getMidnights(epoch_start, epoch_end))
console.log('* check it *')
console.log(getMidnights(epoch_start, epoch_end).map(t => new Date(t*1e3)));

  • Related