Skip to content

Instantly share code, notes, and snippets.

@ivan-loh
Created July 11, 2015 18:06
Show Gist options
  • Select an option

  • Save ivan-loh/41215fa342189dbc340e to your computer and use it in GitHub Desktop.

Select an option

Save ivan-loh/41215fa342189dbc340e to your computer and use it in GitHub Desktop.
javascript - get date to closest x minutes
function getRange() {
var lower = getLowerClosest(10);
var upper = getHigherClosest(10);
return moment(lower).format('HH:mm:ss') + ' - ' + moment(upper).format('HH:mm:ss');
}
function getLowerClosest(mins) {
var coeff = 1000 * 60 * mins;
var date = new Date();
return new Date(Math.floor(date.getTime() / coeff) * coeff);
}
function getHigherClosest(mins) {
var coeff = 1000 * 60 * mins;
var date = new Date();
return new Date(Math.ceil(date.getTime() / coeff) * coeff);
}
function getClosest(mins) {
var coeff = 1000 * 60 * mins;
var date = new Date();
return new Date(Math.round(date.getTime() / coeff) * coeff);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment