Open In App

How to Round off Time to Nearest 5 Min using JavaScript?

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To round off time to the nearest 5 minutes in JavaScript, extract the minutes from a Date object, round them to the nearest multiple of 5, and set the updated time back into the Date object.

Below are the approaches to round off time to the nearest 5 minutes:

Approach 1: Using Math.floor() function

In this approach, both options are available to either round down or round up the date object. This example uses the basic Math.floor() function and Math.ceil() function to perform the operation.

Example: This example implements the above approach.

JavaScript
let date = new Date();

console.log("Initial Date: ", date);

function roundDownDate() {
    let coff = 1000 * 60 * 5; // milliseconds in 5 minutes
    let roundedDownDate = 
    	new Date(Math.floor(new Date() / coff) * coff);
    console.log("Rounded Down Date: ", roundedDownDate);
}

function roundUpDate() {
    let coff = 1000 * 60 * 5; // milliseconds in 5 minutes
    let roundedUpDate = new Date(Math.ceil(new Date() / coff) * coff);
    console.log("Rounded Up Date: ", roundedUpDate);
}

roundDownDate();
roundUpDate();

Output
Initial Date:  2024-10-14T09:24:52.076Z
Rounded Down Date:  2024-10-14T09:20:00.000Z
Rounded Up Date:  2024-10-14T09:25:00.000Z

Approach 2: Using Math.round() function

This approach uses basic Math.round() function to perform the operation. Calculate the milliseconds in 5 minutes, divide the date object by milliseconds and get the round value then again multiply the milliseconds.

Example: This example implements the above approach.

JavaScript
let date = new Date();

console.log("Original Date: ", date);

function roundOff() {
    let coff = 1000 * 60 * 5; // milliseconds in 5 minutes
    let roundedDate = new Date(Math.round(date.getTime() / coff) * coff);
    console.log("Rounded Date: ", roundedDate);
}

roundOff();

Output
Original Date:  2024-10-14T09:25:00.654Z
Rounded Date:  2024-10-14T09:25:00.000Z


Next Article

Similar Reads