Reputation: 75
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);
Upvotes: 2
Views: 1302
Reputation: 24280
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);
Upvotes: 1
Reputation: 3408
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);
Upvotes: 4