Javascript 如何使用 moment.js 将分钟转换为小时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36035598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:32:38  来源:igfitidea点击:

how to convert minutes to hours using moment.js

javascriptmomentjs

提问by user1268130

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

谁能告诉我如何使用 moment.js 将分钟转换为小时并以 hh:mm A 格式显示。

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

例如,如果分钟是 480,它应该将输出显示为 08:00 AM。如果分钟为 1080,则应将输出显示为 06:00 PM

回答by Maggie Pint

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.

UTC 的使用避免了夏令时转换的问题,这会导致时间根据相关日期而变化。

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:

如果您确实想要指定日期午夜后的分钟数,包括 DST 转换,请取出 utc 并使用:

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:

请注意,接受的答案在 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.

编辑:原始答案已更新以修复错误。作为额外的评论,我对任何试图将分钟数映射到民用时间的代码都非常谨慎。最重要的是,一天中的 480 分钟并不总是上午 8:00。在您的问题的背景下考虑这一点。DST 错误现在很可能出现。

回答by user162097

You can just do the basic arithmetic like so:

你可以像这样进行基本的算术运算:

function getTimeFromMins(mins) {
    // do not include the first validation check if you want, for example,
    // getTimeFromMins(1530) to equal getTimeFromMins(90) (i.e. mins rollover)
    if (mins >= 24 * 60 || mins < 0) {
        throw new RangeError("Valid input should be greater than or equal to 0 and less than 1440.");
    }
    var h = mins / 60 | 0,
        m = mins % 60 | 0;
    return moment.utc().hours(h).minutes(m).format("hh:mm A");
}


getTimeFromMins(480); // returns "08:00 AM"
getTimeFromMins(520); // returns "08:40 AM"
getTimeFromMins(1080); // returns "06:00 PM"