Open In App

How to Round MomentJS Time to Nearest 30-Minute Interval?

Last Updated : 27 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

If we want to round the time to the nearest 30-minute interval, we can do this in JavaScript with the help of MomentJS. Rounding time to the nearest 30-minute interval is used to schedule tasks, book appointments, etc. Suppose we have an appointment at 10:22 AM, we might want to round it to 10:30 AM. Or if we have a task scheduled at 3:47 PM, you might want to round it to 4:00 PM. we are going to discuss how we can use Moment.js to round time to the nearest 30-minute interval.

Installing Moment.js in Node.js

We have to first install moment.js using the following command in the terminal:

npm install moment

Below are different possible approaches using which we can round time to the nearest 30-minute interval using MomentJS:

Using Custom Rounding Logic

In this approach, we will create a custom function that calculates the nearest 30-minute mark. We use Moment.js to handle the time, and then adjust the minutes. This approach involves manually calculating the minutes and adjusting it.

Example: This example shows the creation of a custom function that is used to round off the time.

JavaScript
const moment = require("moment");

function fun(momentTime) {
  let minutes = momentTime.minutes();
  let roundedMinutes = Math.round(minutes / 30) * 30;
  return momentTime.minutes(roundedMinutes).seconds(0);
}

let time = moment("2024-07-14 14:22:00");
let roundedTime = fun(time);
console.log("Original Time:", time.format("YYYY-MM-DD HH:mm:ss"));
console.log("Rounded Time:", roundedTime.format("YYYY-MM-DD HH:mm:ss"));

Output:

Original Time: 2024-07-14 14:22:00
Rounded Time: 2024-07-14 14:30:00

Using Built-in MomentJS Methods

Moment.js has several built-in methods for manipulating time, but it does not directly support rounding to the nearest 30-minute interval. However, we can combine its methods to achieve similar results.

Example: Below is code where we are going to use Moment.JS's built-in methods to approximate rounding.

JavaScript
const moment = require("moment");

function fun(momentTime) {
  let minutes = momentTime.minutes();
  let roundedMinutes = Math.round(minutes / 30) * 30;
  return momentTime.clone().minute(roundedMinutes).second(0);
}

let time = moment("2024-07-14 14:22:00");
let roundedTime = fun(time);
console.log("Original Time:", time.format("YYYY-MM-DD HH:mm:ss"));
console.log("Rounded Time:", roundedTime.format("YYYY-MM-DD HH:mm:ss"));

Output:

Original Time: 2024-07-14 14:22:00
Rounded Time: 2024-07-14 14:30:00

Similar Reads