MitchEff
MitchEff

Reputation: 1557

Moment.js duration is completely incorrect

I'm running this exact code, and momentjs is getting the number of hours entirely incorrect:

   const minutes = 2100
   const duration = moment.duration(minutes, 'minutes')
   const inHours = duration.hours()

   console.log(inHours)

The answer is clearly 35, but it's just saying 11.

There's not really much more context I can provide here, as it's really something very basic.

Where might this be going wrong?

Upvotes: 4

Views: 442

Answers (2)

SoWhat
SoWhat

Reputation: 5622

Moment Duration will convert it into days, hours, minutes, seconds

2100 minutes = 35 hrs = 24 + 11 hrs = 1 day + 11 hours

If you type duration.days(), it will give you 1.

If you want the duration as hours, you can do : duration.asHours()

A far more performance optimized new generation code that is also thread safe for doing this would be: var hours = 2100/60

Upvotes: 6

Royts
Royts

Reputation: 511

You can directly get the hours by using .asHours()

const minutes = 2100
const duration = moment.duration(minutes, 'minutes').asHours()
console.log(duration)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Upvotes: 2

Related Questions