Search code examples
javascriptdatetimeutc

How to create bounds of a timeframe around microtime in JavaScript?


I have a timestamp in microseconds, 1279408157000439, I want to find the lower bound to the closest arbitrary timeframe and the upper bound.

So, if my timeframe is minute, I want to find the timestamp (in microseconds) that corresponds to the minute that includes this timestamp up to the microsecond before the minute after this timestamp.

I'm using JavaScript. Any help would be greatly appreciated.

Thanks!


Solution

  • You can use the math floor and ceiling functions to accomplish this.

    var ts = 1279408157000439; // in microseconds
    var interval = 60000000; // microseconds in one minute
    
    var lowerBound = Math.floor(ts/interval) * interval;
    var upperBound = Math.ceil(ts/interval) * interval;
    
    // account for case where we are exactly on the boundary line
    if (upperBound === lowerBound) upperBound += interval;