Javascript: Round Time UP the next 5 minutes

I need to be able to round the time to the next 5 minutes.

Time 11:54 - hours 11:55

Time 11:56 - hours 12:00

He can never round always always until the next time.

I am using this code at the moment, but it will also be rounded

var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(Math.round(date.getTime() / time) * time);
0
source share
5 answers

Add 2.5 minutes to your time, then a round.

11:54 + 2.5 = 11:56:30 -> 11:55
11:56 + 2.5 = 11:58:30 -> 12:00
+8
source

You can divide 5, make Math.ceil, and then multiply by5

minutes = (5 * Math.ceil(minutes / 5));
+6
source
var b = Date.now() + 15E4,
    c = b % 3E5;
    rounded = new Date(15E4>=c?b-c:b+3E5-c);
+1

, , :

var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(date.getTime() - (date.getTime() % time));

, - :

var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(date.getTime() + time - (date.getTime() % time));
+1
source

With ES6 and partial features, this can be elegant:

const roundDownTo = roundTo => x => Math.floor(x / roundTo) * roundTo;
const roundUpTo = roundTo => x => Math.ceil(x / roundTo) * roundTo;
const roundUpTo5Minutes = roundUpTo(1000 * 60 * 5);

const ms = roundUpTo5Minutes(new Date())
console.log(new Date(ms)); // Wed Jun 05 2019 15:55:00 GMT+0200
0
source

Source: https://habr.com/ru/post/1685210/


All Articles