最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Number of hours to HH:MM with Moment.js (or without) - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited May 21, 2019 at 18:11 Karol Selak asked May 19, 2017 at 11:21 Karol SelakKarol Selak 4,7748 gold badges40 silver badges68 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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')
let hour = 10;
let minute = 30;

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

// output: 10:30
发布评论

评论列表(0)

  1. 暂无评论