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

2

5

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?

Validate answered 19/5, 2017 at 11:21 Comment(0)
V
21

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')
Validate answered 19/5, 2017 at 11:26 Comment(1)
Please note that this fails for numbers over 24 as moment then refers to this value as 1 day. e.g. moment.utc(24*3600*1000).format('HH:mm') => '00:00' Logorrhea
D
-1
let hour = 10;
let minute = 30;

moment({ hour, minute }).format('HH:mm');

// output: 10:30
Dale answered 12/12, 2023 at 14:9 Comment(1)
This doesn't account for the time zone issue and ignores the fact that OP is using a float for hours, not hours and minutes.Lexicostatistics

© 2022 - 2025 — McMap. All rights reserved.