Skip to content

Instantly share code, notes, and snippets.

@ralexandr
Last active May 31, 2018 22:35
Show Gist options
  • Save ralexandr/6dfb1a49b767ebec427e30dede0b8872 to your computer and use it in GitHub Desktop.
Save ralexandr/6dfb1a49b767ebec427e30dede0b8872 to your computer and use it in GitHub Desktop.
Get nearest period (with moment.js)
function nearestMinutes(interval, someMoment) {
const roundedMinutes = Math.round(someMoment.clone().minute() / interval) * interval;
return someMoment.clone().minute(roundedMinutes).second(0);
}
function nearestPastMinutes(interval, someMoment) {
const roundedMinutes = Math.floor(someMoment.minute() / interval) * interval;
return someMoment.clone().minute(roundedMinutes).second(0);
}
function nearestFutureMinutes(interval, someMoment) {
const roundedMinutes = Math.ceil(someMoment.minute() / interval) * interval;
return someMoment.clone().minute(roundedMinutes).second(0);
}
const now = moment();
const nearest5min = nearestMinutes(5, now);
const nearest15min = nearestMinutes(15, now);
const nearest30min = nearestMinutes(30, now);
const nearestFuture5min = nearestFutureMinutes(5, now);
const nearestPast5min = nearestPastMinutes(5, now);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment