Muirik
Muirik

Reputation: 6289

Rounding Up Minute at 30 Seconds and Flooring

I have a time value that looks like so: totalDuration: 00:22:53. What I want to do is round up the seconds on this value when the seconds >= 30 so that it's rounded up to the next minute and zeroed on the seconds.

In other words, my example of 00:22:53 should end up being 00:23:00.

To do that I tried this:

const timeRoundedUp = moment(totalDuration).add(1, 'm').startOf('minute');

But this gives me a null result.

I also tried this:

const roundedUp = moment(totalDuration).add(1, 'minutes');

But that also gives me a null result.

Maybe the issue is the format of the value I am inputting into the function? How can I achieve this?

Upvotes: 0

Views: 177

Answers (1)

tsu
tsu

Reputation: 1261

You must specify the format of your duration for the moment initialize the right object

let totalDuration = '00:22:53'
const m = moment(totalDuration, "hh:mm:ss");

// conditionally round the seconds
const roundUp = m.second() >= 30 ? m.add(1, 'minute').startOf('minute') : m.startOf('minute')

console.log(roundUp.format("HH:mm:ss"));

Upvotes: 2

Related Questions