VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-round-up-round-down-a-moment-to-nearest-minute/

⇱ How to Round up/ Round down a Moment to Nearest Minute? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Round up/ Round down a Moment to Nearest Minute?

Last Updated : 26 Aug, 2024

To round a moment object to the nearest minute using Moment.js, and check if the seconds are less than 30 to determine if you should round down to the start of the minute or round up to the next minute.

Below are the approaches to round up/down a moment.js moment to the nearest minute:

Rounding Up (Ceil)

In this rounding up means we move to the next full minute. Rounding up in the ceiling means we are taking time to up. For example, if the time is 2:34:30 PM, rounding up will give you 2:35 PM.

Syntax:

moment().startOf('minute').add(1, 'minute');

Example : This code uses the moment library to round up a given time to the next minute and then format it as HH:mm

Output:

14:35

Rounding Down (Floor)

Rounding down means we are going to the previous full minute. For example, if the time is 2:34:45 PM, rounding down will give you 2:34 PM.

Syntax:

moment().startOf('minute');

Example: This code rounds down the given time to the start of the minute and formats it as HH:mm

Output:

14:34

Rounding to the Nearest Minute

Rounding to the nearest minute means we are adjusting the time either up or down based on whether the seconds are closer to the next minute or the current minute. For example, 2:34:30 PM will round up to 2:35 PM, while 2:34:15 PM will round down to 2:34 PM.

Syntax:

moment().seconds() < 30 ? moment().startOf('minute') : moment().startOf('minute').add(1, 'minute');

Example: This code rounds the given time to the nearest minute based on whether the seconds are less than 30 or not, and formats it as HH:mm.

Output:

14:35
Comment
Article Tags: