Rounding up a dateTime to the nearest X minutes

Hey All,

Just found this little article that uses some simple JS to take a dateTime input and either round it, or round it up to the nearest 15 minute interval.

I modified it slightly so you could change the minutes input (i.e. round to nearest 15 minutes, or 60 minutes etc) and also configured it if you wanted to round or round up.

I added into my growing list of simple functions i’ve added into a collection of custom modules, but thought i’d share the code in case someone found it helpful.

Here’s the code from the JS file in the modules folder:

const roundTime = function roundToNearest15(timestamp, roundMins, roundUp) {
    if (roundUp == true) {
        let date = new Date(timestamp);
        const ms = 1000 * 60 * roundMins;
        return new Date(Math.ceil(date.getTime() / ms) * ms);
    } else {
        let date = new Date(timestamp);
        const ms = 1000 * 60 * roundMins;
        return new Date(Math.round(date.getTime() / ms) * ms);
    }

}

exports.roundTime = function (options) {
    options = this.parse(options);
    return roundTime(options.timestamp, options.roundMins, options.roundUp);
}

And here is the code from the HJSON file:

{
    type: 'roundTime',
    module : 'functions',
    action : 'roundTime',
    groupTitle : 'Functions',
    groupIcon : 'fa-fw fal fa-function comp-data',
    title : 'Round Time',
    icon : 'fal fa-lg fa-clock comp-data',
    dataPickObject: true,
   properties : [
    {
      group: 'Properties',
      variables: [
        { name: 'actionName', optionName: 'name', title: 'Name', type: 'text', required: true, defaultValue: ''},
          { name: 'output', optionName: 'output', title: 'Output', type: 'boolean', defaultValue: false },
          { name: 'timestamp', optionName: 'timestamp', title: 'Timestamp', type: 'text', required: true, defaultValue: '', serverDataBindings: true, help: 'DateTime timestamp to round'},
          { name: 'roundMins', optionName: 'roundMins', title: 'Round Minutes', type: 'text', required: true, defaultValue: '', serverDataBindings: true, help: 'Minutes to round to.'},                      
          { name: 'roundUp', optionName: 'roundUp', title: 'Round Up?', type: 'boolean', required: true, defaultValue: 'false', serverDataBindings: true, help: 'Always round up to nearest time.'},
                    
      ]
    }
  ]
  }

Just something simple that I found useful and wanted to share.

Enjoy!

6 Likes