javascript Moment.js 以 dd:hh:mm:ss 格式获取两个日期之间的差异?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28657113/
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
Moment.js Get difference between two dates in the dd:hh:mm:ss format?
提问by JohnWick
I am calculating the time until 11:59PM of the current day. Here is an example.
我正在计算直到当天晚上 11:59 的时间。这是一个例子。
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.js"></script>
<script>
setInterval(function() {
var now = moment();
var mid = moment();
mid = mid.endOf('day');
var diffHours = mid.diff(now, 'hours');
var diffMinutes = mid.diff(now, 'minutes');
var diffSeconds = mid.diff(now, 'seconds');
console.log(diffHours + "h " + diffMinutes + "m " + diffSeconds + "s");
}, 1000)
</script>
However, I was hoping it would show me a time such as 20h 13m 49s, instead I am getting 20h 1255m 73500s
但是,我希望它会显示一个时间,例如 20h 13m 49s,而不是我得到 20h 1255m 73500s
I understand this is working as intended pretty much, but how can I achieve the format I am seeking?
我知道这几乎按预期工作,但我怎样才能实现我正在寻求的格式?
回答by Nit
You'll want to modify your now
variable after each diff
.
您需要now
在每个diff
.
var hours = mid.diff(now, 'hours'); //Get hours 'till end of day
now.hours(now.hours() + hours);
var minutes = mid.diff(now, 'minutes');
回答by RobG
Just for comparison, here's David Stampher's moment.js example from a comment on another answer giving the time until 23:59:59.999 "today" and the same functionality in plain JS:
只是为了比较,这里是 David Stampher 的 moment.js 示例,来自对另一个答案的评论,给出了直到 23:59:59.999“今天”的时间和普通 JS 中的相同功能:
// Moment.js version
var now = moment();
var mid = moment();
mid = mid.endOf('day');
var diff1 = moment.utc(moment(mid, "DD/MM/YYYY HH:mm:ss")
.diff(moment(now, "DD/MM/YYYY HH:mm:ss")))
.format("HH:mm:ss");
console.log('moment.js: ' + diff1);
// POJS version
var z = (n) => (n<10? '0' : '') + n;
var ms = new Date().setHours(23,59,59,999) - new Date();
var diff2 = z(ms/3.6e6|0) + ':' +
z(ms%3.6e6/6e4|0) + ':' +
z(ms%6e4/1e3|0);
console.log('plain js : ' + diff2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>