Borislav Hadzhiev
Sun Jan 16 2022·2 min read
Photo by Julia Caesar
To round time to the nearest minute:
Math.round()
function.function roundToNearestMinute(date = new Date()) { const minutes = 1; const ms = 1000 * 60 * minutes; // 👇️ replace Math.round with Math.ceil to always round UP return new Date(Math.round(date.getTime() / ms) * ms); } // 👇️ Thu Jan 13 2022 08:30:00 (seconds are 29) console.log(roundToNearestMinute(new Date(2022, 0, 13, 8, 30, 29))); // 👇️ Thu Jan 13 2022 08:31:00 (minutes are 30) console.log(roundToNearestMinute(new Date(2022, 0, 13, 8, 30, 30)));
We used the
Date()
constructor when logging the examples to the console. The parameters we passed
are: year
, month
(January = 0, February = 1, etc), day of month
, hours
,
minutes
, seconds
.
We created a reusable function that rounds a date to the nearest minute.
Date
object as a parameter or uses the current date and time if no parameter is provided.If you always want to round up, replace the Math.round()
function with
Math.ceil()
.
The ms
variable stores the number of milliseconds there are in 1
minute.
The getTime method returns the number of milliseconds since the Unix Epoch.
We divide the result by the number of milliseconds in 1
minute and round to
the nearest integer using the
Math.round
function.
Here are some examples of how Math.round
works.
console.log(Math.round(2.49)); // 👉️ 2 console.log(Math.round(2.5)); // 👉️ 3
The function rounds the number up or down to the nearest integer.
0.5
, it gets rounded to the next higher absolute value.If the number is positive and its fractional portion is less than 0.5
, it gets
rounded to the lower absolute value.
If you always want to round up to the next minute, use the Math.ceil function instead.
function roundToNearestMinute(date = new Date()) { const minutes = 1; const ms = 1000 * 60 * minutes; return new Date(Math.ceil(date.getTime() / ms) * ms); } // 👇️ Thu Jan 13 2022 08:31:00 (seconds are 29) console.log(roundToNearestMinute(new Date(2022, 0, 13, 8, 30, 29))); // 👇️ Thu Jan 13 2022 08:31:00 (minutes are 30) console.log(roundToNearestMinute(new Date(2022, 0, 13, 8, 30, 30)));
The Math.ceil
function returns the smallest integer that is greater than or
equal to the provided number.
console.log(Math.ceil(2.1)); // 👉️ 3 console.log(Math.ceil(2.0001)); // 👉️ 3
In short, if there is anything after the decimal, the number will get rounded to the next integer, otherwise the number is returned.
The last step is to multiply the value from calling Math.round
or Math.ceil
with the number of milliseconds there are in a minute and pass the result to the
Date()
constructor.
The roundToNearestMinute
function returns a new Date
object rounding the
seconds to the nearest whole minute.