将日期时间四舍五入到最后 10 分钟 JavaScript

Round datetime to the last 10 minutes JavaScript

我的应用程序需要当前日期时间。但我需要将其四舍五入到最接近的 10 分钟。我用 Math.round 完成了这个。问题是我需要它舍入到最后 10 分钟。没到下一个。因为我还没有那个数据。

例如:

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

我该怎么做?

const coeff = 1000 * 60 * 10;
const date = new Date();  //or use any other date
let roundDate = new Date(Math.round(date.getTime() / coeff) * coeff);

使用 Math.floor 但将值除以 10,然后乘以 10。

示例:

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

日期示例:

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

let min = date.getMinutes();
date.setMinutes(Math.floor(min / 10) * 10);
console.log(date);

您可以使用 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);