计算两个不同日期两次的时间差 [英] Calculate the difference between two times on two different days
问题描述
我试图确定两次之间的时间差,我将它们表示为无符号整数(以斜线表示),如下所示:
I am trying to determine the time difference between two times, which i represent as unsigned integers (in a sturct) as follows:
unsigned int day;
unsigned int month;
unsigned int year;
unsigned int hour;
unsigned int mins;
unsigned int seconds;
我可以轻松地计算出同一天两次发生的分钟之间的时差:这不是我的确切代码,这只是背后的逻辑。
i can work out the time difference in minutes between two times that occur on the same day easily enough using: This isn't my exact code, this is just the logic behind it.
time1 = hours*3600 + mins*60 + seconds;
time1 = hours2*3600 + mins2*60 + seconds2;
//time2 will always be less than time1
time_diff_secs = time1_secs - time2_secs;
time_diff_mins = time_diff_secs / 60;
time_diff_secs = time_diff_secs % 60;
这会产生以下输出:
Time mayday was issued: 13 Hours 4 Mins 0 Seconds
Time mayday was recieved: 13 Hours 10 Mins 0 Seconds
Time between sending and receiving: 6.00Mins
这是正确的,但是当我在不同的日子有两次时,得到的结果是:
which is correct, but when I have two times that are on different days I get this as the result:
Time mayday was issued: 23 Hours 0 Mins 0 Seconds
Time mayday was recieved: 0 Hours 39 Mins 38 Seconds
Time between sending and receiving: 71581448.00Mins
这显然是错误的,我不确定该如何进行从这里开始,实际结果应该是40分钟,而不是7150万。
This is obviously incorrect, I am not sure how to progress from here, the actual result should be 40mins, not 71.5million.
推荐答案
您将出现下溢情况。尝试执行此操作(不管变量是 signed
还是 unsigned
,都可以运行):
You are getting an underflow. Try this (works regardless of whether the variables are signed
or unsigned
):
if (time1_secs < time2_secs) {
// New day. Add 24 hours:
time_diff_secs = 24*60*60 + time1_secs - time2_secs;
} else {
time_diff_secs = time1_secs - time2_secs;
}
time_diff_mins = time_diff_secs / 60;
time_diff_secs = time_diff_secs % 60;
这篇关于计算两个不同日期两次的时间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!