2

For my application is need the current datetime. But I need to round that to the nearest 10 min. I accomplished this with Math.round. The problem is that I need it to round to the LAST 10 min. Not up to the next. Because I won't have that data yet.

For example:

16:33 = 16:30 || 16:38 = 16:30 || 16:41 = 16:40

How can I do this?

const coeff = 1000 * 60 * 10;
const date = new Date();  //or use any other date
let roundDate = new Date(Math.round(date.getTime() / coeff) * coeff);
Trisha
  • 75
  • 8
  • I think you answered your own question, your code is working: https://stackoverflow.com/questions/10789384/round-a-date-to-the-nearest-5-minutes-in-javascript – Pingolin Jan 03 '19 at 14:03

2 Answers2

4

Use Math.floor but divide the value by 10, then multiply by 10.

Example:

var x = 11;
console.log(Math.floor(x / 10) * 10);

Date Example:

let date = new Date();
console.log(date);

let min = date.getMinutes();
date.setMinutes(Math.floor(min / 10) * 10);
console.log(date);
basic
  • 3,348
  • 3
  • 21
  • 36
1

You can use Math.floor():

const coeff = 1000 * 60 * 10;
const date = new Date("2019-01-03T13:18:05.641Z");

let floorDate = new Date(Math.floor(date.getTime() / coeff) * coeff);

console.log(date);
console.log(floorDate);
Peter B
  • 22,460
  • 5
  • 32
  • 69