Open In App

Moment.js Customize Relative Time Rounding

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Moment.js is a JavaScript date library for parsing, validating, manipulating, and formatting dates. Moment.js Customize Relative Time Rounding is used to round off time as per the requirement. Here, relative means the time would be rounded-off with respect to the current time. We can control the rounding using moment.relativeTimeRounding.

Syntax:

moment.relativeTimeRounding( function );

Parameters: This method accepts a single parameter that specified the kind of rounding that needs to be done. Some of the available parameters are listed below:

  • Math.ceil will round relative time evaluation up.
  • Math.floor will round relative time evaluation down.

Return Value: This function returns the time rounded off to the current time.

Note: This will not work in the normal Node.js program because it requires the moment.js library to be installed.

Moment.js can be installed using the following command:

npm install moment

Example 1: Here, we will be rounding down to one hour behind of current time. For this, we need to pass Math.floor as a parameter.

Javascript




const moment = require("moment");
  
// Round relative time evaluation down
moment.relativeTimeRounding(Math.floor);
  
let a = moment();
a.toNow(); // Current time
console.log("Current time is:", a);
  
// Rounding-down time to one-hr behind
a.subtract({ minutes: 59 });
console.log("Rounded-down time is:", a);


Output:

Current time is:  Moment<2022-11-30T19:38:20+05:30>
Rounded-down time is:  Moment<2022-11-30T18:39:20+05:30>

Example 2: Here, we will be rounding up to one day ahead of the current time. For this, we need to pass Math.ceil as the parameter.

Javascript




const moment = require("moment");
  
// Round relative time evaluation up
moment.relativeTimeRounding(Math.ceil);
  
let a = moment();
a.toNow();
console.log("Current time is: ", a);
  
// Rounding-up time to one-day ahead
a.add({ hours: 23, minutes: 59, seconds: 59 });
console.log("Rounded-up time is: ", a);


Output:

Current time is:  Moment<2022-11-30T19:41:59+05:30>
Rounded-up time is:  Moment<2022-12-01T19:41:58+05:30>

References: https://momentjs.com/docs/#/customization/relative-time-rounding



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads