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

Given a JavaScript date and the task is to round it to 5 minutes with the help of JavaScript. There are two approaches that are discussed below:
Approach 1: In this approach, both options are available to either round down or round up the date object. This example uses basic Math.floor() function and Math.ceil() function to perform the operation.
- Example: This example implements the above approach.
<!DOCTYPE html><html><head><title>Round off a Date Object to 5minutes in JavaScript.</title></head><bodystyle="text-align:center;"><h1style="color:green;">zambiatek</h1><pid="gfg"style="font-size: 20px;font-weight: bold"></p><buttononclick="GFG_Fun1();">Round Down</button><buttononclick="GFG_Fun2();">Round Up</button><pid="zambiatek"style="font-size: 26px;font-weight: bold;color: green;"></p><script>var up = document.getElementById('gfg');var down = document.getElementById('zambiatek');var date = new Date();up.innerHTML = "Click on the button to "+ "round the date as specified."+ "<br><br>Date - " + date;function GFG_Fun1() {// ms in 5 minutes.var coff = 1000 * 60 * 5;down.innerHTML = new Date(Math.floor(date / coff) * coff);}function GFG_Fun2() {// ms in 5 minutes.var coff = 1000 * 60 * 5;down.innerHTML = new Date(Math.ceil(date / coff) * coff);}</script></body></html> -
Output:
Approach 2: This example 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.
<!DOCTYPE html><html><head><title>Round off a Date Object to 5minutes in JavaScript.</title></head><bodystyle="text-align:center;"><h1style="color:green;">zambiatek</h1><pid="GFG_UP"style="font-size: 20px;font-weight: bold"></p><buttononclick="GFG_Fun();">click here</button><pid="GFG_DOWN"style = "font-size: 26px;font-weight: bold;color: green;"></p><script>var up = document.getElementById('GFG_UP');var down = document.getElementById('GFG_DOWN');var date = new Date();up.innerHTML = "Click on the button to "+ "round the date as specified."+ "<br><br>Date - " + date;function GFG_Fun() {// ms in 5 minutes.var coff = 1000 * 60 * 5;down.innerHTML = new Date(Math.round(date.getTime() / coff) * coff);}</script></body></html> -
Output:
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!




