Round Moment.js to previous interval

Round Moment.js to previous interval

When working with dates and times it's not unusual to restrict the options a user can choose. For example when presenting the user with a dropdown of times to choose from, but only allow 5min intervals. You want to add a sensible default, for example the previous interval. So when the user opens the dialog at 09:02 the default should be 09:00.

It's possible to do this with Moment.js and it's duration function:

export function floorToInterval(date: Moment, interval: number, unit: DurationConstructor) {
  const duration = moment.duration(interval, unit);
  return moment(Math.floor((+date) / (+duration)) * (+duration));
}

A call of the function would look like this:

const defaultTime = floorToInterval(moment(), 5, 'minutes');

When exchanging the floor function with ceil, you can do the same but for the next interval instead of the previous one.

export function ceilToInterval(date: Moment, interval: number, unit: DurationConstructor) {
  const duration = moment.duration(interval, unit);
  return moment(Math.ceil((+date) / (+duration)) * (+duration));
}