Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of hours to HH:MM with Moment.js (or without)

I have very simple problem, but couldn't find good simple DRY solution. I want to convert number of hours to HH:MM format. My try with Moment.js is:

var hours = 10.5
var hour_string = moment(hours*3600*1000).format('HH:MM')

But unfortunately I get:

"11:01"

and have no idea why. Of course my wanted result is "10:30".

I'd like just do it in the easiest way, similar as I can do in Rails:

Time.at(hours*3600).utc.strftime("%H:%M")

Any ideas?

like image 286
Karol Selak Avatar asked Dec 03 '22 22:12

Karol Selak


1 Answers

Okay, I found the reason. "MM" means months, not minutes, which are "mm". And the hour shift was caused by timezones, which we can omit using the utc function. The final solution is:

moment.utc(hours*3600*1000).format('HH:mm')
like image 113
Karol Selak Avatar answered Dec 11 '22 16:12

Karol Selak