Javascript 以 HH:mm 格式计算时差

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12193342/
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 07:21:55  来源:igfitidea点击:

calculate time difference in HH:mm format

javascripttimestamp

提问by davioooh

I have two timestamps in HH:mmformat and I need to calculate difference between them representing the time interval in the same HH:mmformat.

我有两个HH:mm格式的时间戳,我需要计算它们之间的差异,表示相同HH:mm格式的时间间隔。

Is there any utility in JavaScript to achieve this? I tried using Dateobject, but I cannot find something useful... Can you help me?

JavaScript 中是否有任何实用程序可以实现这一点?我尝试使用Date对象,但找不到有用的东西...你能帮我吗?

回答by Konerak

You can just substract two Dates from one another, the result will be the difference in milliseconds.

您可以将两个日期相减,结果将以毫秒为单位。

From the Mozilla Developer Network:

来自Mozilla 开发者网络:

// using static methods
var start = Date.now();
// the event you'd like to time goes here:
doSomethingForALongTime();
var end = Date.now();
var elapsed = end - start; // time in milliseconds

Since Date has a constructor that accepts milliseconds as an argument, you can re-convert this to a Date by just doing

由于 Date 有一个接受毫秒作为参数的构造函数,您可以通过执行以下操作将其重新转换为 Date

var difference = new Date(elapsed);
//If you really want the hours/minutes, 
//Date has functions for that too:
var diff_hours = difference.getHours();
var diff_mins = difference.getMinutes();

回答by timidboy

Something like this:

像这样的东西:

?var t1 = '12:04'.split(':'), t2 = '3:45'???????.split(':');
var d1 = new? Date(0, 0, 0, t1[0], t1[1]),
    d2 = new Date(0, 0, 0, t2[0], t2[1]);
var diff = new Date(d1 - d2);

回答by The Kaizer

You could try this

你可以试试这个

https://github.com/layam/js_humanized_time_span

https://github.com/layam/js_humanized_time_span

and format the output?

并格式化输出?

or if using jquery you can try

或者如果使用 jquery 你可以试试

http://timeago.yarp.com/

http://timeago.yarp.com/

回答by Graphic Equaliser

Assuming tim1 is a string like "09:15" and tim2 is a string like "19:05", then the difference between tim2 and tim1 could be derived with the following javascript code :-

假设 tim1 是一个像“09:15”这样的字符串,而 tim2 是一个像“19:05”这样的字符串,那么 tim2 和 tim1 之间的差异可以通过以下 javascript 代码得出:-

var tim1='09:15',tim2='19:05';
var ary1=tim1.split(':'),ary2=tim2.split(':');
var minsdiff=parseInt(ary2[0],10)*60+parseInt(ary2[1],10)-parseInt(ary1[0],10)*60-parseInt(ary1[1],10);
alert(String(100+Math.floor(minsdiff/60)).substr(1)+':'+String(100+minsdiff%60).substr(1));