Categories
JavaScript Answers

How to round up or down a moment.js to the nearest minute with JavaScript?

Spread the love

Sometimes, we want to round up or down a moment.js to the nearest minute with JavaScript.

In this article, we’ll look at how to round up or down a moment.js to the nearest minute with JavaScript.

How to round up or down a moment.js to the nearest minute with JavaScript?

To round up or down a moment.js to the nearest minute with JavaScript, we use the startOf method.

For instance, we write

const roundDown = moment("2022-02-17 12:59:59").startOf("hour");
roundDown.format("HH:mm:SS");

to round up to the nearest hour by calling startOf.

Then we write

const roundUp = (momentObj, roundBy) => {
  return momentObj.add(1, roundBy).startOf(roundBy);
};

const a = moment("2022-02-17 12:00:00");
const roundedUp = roundUp(a, "minute").format("HH:mm:SS");

to define the roundUp function.

In it, we call add with 1 and roundBy to add 1 roundBy unit to the moment object.

Then we call startOf with roundBy to round to the nearest roundBy unit.

Next we call roundUp and format to round up and format the time returned.

Conclusion

To round up or down a moment.js to the nearest minute with JavaScript, we use the roundTo method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *