Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Momentjs 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.

Can anyone see where this'd be going wrong?

like image 298
MitchEff Avatar asked Jan 27 '23 05:01

MitchEff


2 Answers

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

like image 161
SoWhat Avatar answered Jan 28 '23 19:01

SoWhat


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>
like image 28
Royts Avatar answered Jan 28 '23 20:01

Royts