javascript Momentjs 中自午夜以来的分钟数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25130128/
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
Minutes since midnight in Momentjs
提问by bguiz
In pure JS, thiswould be how.
在纯 JS 中,这将是如何。
How can I find out the number of minutes since midnight for a given moment
object (without extracting to Date
)?
如何找出给定moment
对象自午夜以来的分钟数(不提取到Date
)?
- Must take into account DSTs
- Minutes should be rounded
- Must work with local time (not convert to UTC)
- 必须考虑 DST
- 分钟应该四舍五入
- 必须使用本地时间(不转换为 UTC)
回答by Tuan
// Your moment
var mmt = moment();
// Your moment at midnight
var mmtMidnight = mmt.clone().startOf('day');
// Difference in minutes
var diffMinutes = mmt.diff(mmtMidnight, 'minutes');
By default, moment#diff will return number rounded down. If you want the floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned rounded number, not a rounded down number.
默认情况下, moment#diff 将返回向下取整的数字。如果您想要浮点数,请将 true 作为第三个参数传递。在 2.0.0 之前,moment#diff 返回四舍五入的数字,而不是四舍五入的数字。
Consider this pseudocode because I haven't test to see if the difference takes into account DST.
考虑这个伪代码,因为我还没有测试看差异是否考虑了夏令时。
回答by bguiz
This is what I have at the moment:
这就是我目前所拥有的:
if (!moment.isMoment(mmt)) {
return 0;
}
var hh = mmt.get('hour');
var mm = mmt.get('minute');
return hh*60 + mm;
I am not sure if it takes into account various edge cases; comment if this is the case, or provide an alternate answer.
我不确定它是否考虑了各种边缘情况;如果是这种情况,请发表评论,或提供替代答案。