Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

javascript - how to convert minutes to hours using moment.js

Can anyone tell me how to convert minutes to hours using moment.js and display in hh:mm A format.

For example, If minutes is 480 it should display output as 08:00 AM. If minutes is 1080 it should display output as 06:00 PM

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming that you always want to add minutes from midnight, the easiest thing to do is:

moment.utc().startOf('day').add(480, 'minutes').format('hh:mm A')

The use of UTC avoids issues with daylight saving time transitions that would cause the time to vary based on the day in question.

If you actually want the number of minutes after midnight on a given day, including the DST transitions take out the utc and just use:

moment().startOf('day').add(480, 'minutes').format('hh:mm A')

Note that the accepted answer has potential issues with DST transitions. For instance if you are in a part of the United States that observes DST:

moment('2016-03-13').hours(2).minutes(30).format('hh:mm A')
"03:30 AM"

The result is not as expected, and will vary between going back and hour or going forward an hour depending on the browser.

Edit: Original answer has been updated to fix bug. As an additional comment, I would be extremely leery of any code that attempts to map a number of minutes to civil time. The bottom line is that 480 minutes into the day is not always 8:00 AM. Consider this in the context of your problem. DST bugs are likely right now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...