Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...