javascript 获取两个日期时间之间的时差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18623783/
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
Get the time difference between two datetimes
提问by Leo
I know I can do anything and some more envolving Dates with momentjs. But embarrassingly, I'm having a hard time trying to do something that seems simple: geting the difference between 2 times.
我知道我可以用 momentjs 做任何事情,甚至可以做一些更复杂的日期。但令人尴尬的是,我很难尝试做一些看起来很简单的事情:找出 2 次之间的差异。
Example:
例子:
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
//expected result:
"00:39:30"
what I tried:
我试过的:
var now = moment("04/09/2013 15:00:00");
var then = moment("04/09/2013 14:20:30");
console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss"))
//outputs 10:39:30
I do not understand what is that "10" there. I live in Brazil, so we are utc-0300 if that is relevant.
我不明白那里的“10”是什么。我住在巴西,所以如果相关,我们是 utc-0300。
The result of moment.duration(now.diff(then))
is a duration with the correct internal values:
的结果moment.duration(now.diff(then))
是具有正确内部值的持续时间:
days: 0
hours: 0
milliseconds: 0
minutes: 39
months: 0
seconds: 30
years: 0
So, I guess my question is: how to convert a momentjs Duration to a time interval? I sure can use
所以,我想我的问题是:如何将 momentjs Duration 转换为时间间隔?我肯定可以用
duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds")
but i feel that there is something more elegantthat I am completely missing.
但我觉得我完全缺少一些更优雅的东西。
update
looking closer, in the above example now
is:
更新
仔细看,在上面的例子中now
是:
Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…}
and moment(moment.duration(now.diff(then)))
is:
并且moment(moment.duration(now.diff(then)))
是:
Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…}
I am not sure why the second value is in Daylight Time (-0200)... but I am sure that i do not like dates :(
我不确定为什么第二个值是夏令时(-0200)...但我确定我不喜欢日期:(
update 2
更新 2
well, the value is -0200 probably because 31/12/1969 was a date where the daylight time was being used... so thats that.
好吧,该值为 -0200 可能是因为 31/12/1969 是使用夏令时的日期......就是这样。
回答by Matt Johnson-Pint
This approach will work ONLY when the total duration is less than 24 hours:
此方法仅在总持续时间少于 24 小时时有效:
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
// outputs: "00:39:30"
If you have 24 hours or more, the hours will reset to zero with the above approach, so it is not ideal.
如果您有 24 小时或更长时间,则使用上述方法将小时数重置为零,因此并不理想。
If you want to get a valid response for durations of 24 hours or greater,then you'll have to do something like this instead:
如果您想获得 24 小时或更长时间的有效响应,则必须执行以下操作:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
// outputs: "48:39:30"
Note that I'm using the utc time as a shortcut. You could pull out d.minutes()
and d.seconds()
separately, but you would also have to zeropad them.
请注意,我使用 UTC 时间作为快捷方式。你可以拉出来d.minutes()
和d.seconds()
分开,但你也必须ZEROPAD他们。
This is necessary because the ability to format a duration
objection is not currently in moment.js. It has been requested here. However, there is a third-party plugin called moment-duration-formatthat is specifically for this purpose:
这是必要的,因为duration
目前在 moment.js 中没有格式化反对意见的能力。 已在此处请求。但是,有一个名为moment-duration-format的第三方插件专门用于此目的:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = d.format("hh:mm:ss");
// outputs: "48:39:30"
回答by TML
Your problem is in passing the result of moment.duration() back into moment() before formatting it; this results in moment() interpreting it as a time relative to the Unix epoch.
您的问题是在格式化之前将 moment.duration() 的结果传回 moment() ;这导致 moment() 将其解释为相对于 Unix 纪元的时间。
It doesn't give you exactly the format you're looking for, but
它没有为您提供您正在寻找的确切格式,但是
moment.duration(now.diff(then)).humanize()
moment.duration(now.diff(then)).humanize()
would give you a useful format like "40 minutes". If you're really keen on that specific formatting, you'll have to build a new string yourself. A cheap way would be
会给你一个有用的格式,比如“40分钟”。如果您真的很喜欢这种特定格式,则必须自己构建一个新字符串。一个便宜的方法是
[diff.asHours(), diff.minutes(), diff.seconds()].join(':')
[diff.asHours(), diff.minutes(), diff.seconds()].join(':')
where var diff = moment.duration(now.diff(then))
. This doesn't give you the zero-padding on single digit values. For that, you might want to consider something like underscore.string- although it seems like a long way to go just for a few extra zeroes. :)
哪里var diff = moment.duration(now.diff(then))
。这不会为您提供单个数字值的零填充。为此,您可能需要考虑像underscore.string之类的东西- 尽管仅仅为了几个额外的零似乎还有很长的路要走。:)
回答by Danilo Colasso
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') //[days, years, months, seconds, ...]
//Result 1
Worked for me
对我来说有效
See more in http://momentjs.com/docs/#/displaying/difference/
回答by Mahima Agrawal
If you want difference of two timestamp into total days,hours and minutes only, not in months and years .
如果您只想将两个时间戳的差异分为总天数、小时数和分钟数,而不是月数和年数。
var now = "01/08/2016 15:00:00";
var then = "04/02/2016 14:20:30";
var diff = moment.duration(moment(then).diff(moment(now)));
diff contains 2 months,23 days,23 hours and 20 minutes. But we need result only in days,hours and minutes so the simple solution is:
diff 包含 2 个月 23 天 23 小时 20 分钟。但是我们只需要几天、几小时和几分钟的结果,所以简单的解决方案是:
var days = parseInt(diff.asDays()); //84
var hours = parseInt(diff.asHours()); //2039 hours, but it gives total hours in given miliseconds which is not expacted.
hours = hours - days*24; // 23 hours
var minutes = parseInt(diff.asMinutes()); //122360 minutes,but it gives total minutes in given miliseconds which is not expacted.
minutes = minutes - (days*24*60 + hours*60); //20 minutes.
Final result will be : 84 days, 23 hours, 20 minutes.
最终结果将是:84 天 23 小时 20 分钟。
回答by Joon
When you call diff
, moment.js calculates the difference in milliseconds.
If the milliseconds is passed to duration
, it is used to calculate duration which is correct.
However. when you pass the same milliseconds to the moment()
, it calculates the date that is milliseconds from(after) epoch/unix time that is January 1, 1970 (midnight UTC/GMT).
That is why you get 1969 as the year together with wrong hour.
当您调用 时diff
,moment.js 以毫秒为单位计算差异。如果将毫秒传递给duration
,则用于计算正确的持续时间。然而。当您将相同的毫秒数传递给 时moment()
,它计算的日期是 1970 年 1 月 1 日(UTC/GMT 午夜)纪元/unix 时间(之后)的毫秒数。这就是为什么您将 1969 年与错误的时间在一起。
duration.get("hours") +":"+ duration.get("minutes") +":"+ duration.get("seconds")
So, I think this is how you should do it since moment.js does not offer format
function for duration. Or you can write a simple wrapper to make it easier/prettier.
所以,我认为这是你应该做的,因为 moment.js 不提供format
持续时间的功能。或者您可以编写一个简单的包装器以使其更容易/更漂亮。
回答by Manzurul
This should work fine.
这应该可以正常工作。
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
console.log(d.days(), d.hours(), d.minutes(), d.seconds());
回答by Filipe Eusébio
If we want only hh:mm:ss, we can use a function like that:
如果我们只想要 hh:mm:ss,我们可以使用这样的函数:
//param: duration in milliseconds
MillisecondsToTime: function(duration) {
var seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(1000*60*60))%24)
, days = parseInt(duration/(1000*60*60*24));
var hoursDays = parseInt(days*24);
hours += hoursDays;
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
回答by Abdus Salam Azad
Use this,
用这个,
var duration = moment.duration(endDate.diff(startDate));
var aa = duration.asHours();
回答by robinvdvleuten
Instead of
代替
Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")
It's better to do
最好这样做
moment.utc(total.asMilliseconds()).format("HH:mm:ss");
回答by skantus
Typescript:following should work,
打字稿:以下应该有效,
export const getTimeBetweenDates = ({
until,
format
}: {
until: number;
format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
const date = new Date();
const remainingTime = new Date(until * 1000);
const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
const diff = getUntil.diff(getFrom, format);
return !isNaN(diff) ? diff : null;
};