计算两个不同日期两次之间的差异

时间:2013-12-03 16:01:03

标签: c time difference

我正在尝试确定两次之间的时差,我将其表示为无符号整数(在sturct中),如下所示:

unsigned int day;
unsigned int month;
unsigned int year;

unsigned int hour;
unsigned int mins;
unsigned int seconds;

我可以很容易地计算出在同一天发生的两次之间的时间差异:这不是我的确切代码,这只是它背后的逻辑。

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

这是正确的,但是当我在不同的日子有两次时,我得到了这个结果:

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分钟,而不是71.5百万。

3 个答案:

答案 0 :(得分:2)

使用标准C库的另一种方法,唯一的优点是你不必担心你的日期重叠多年,或者重叠月份边界+闰年废话的问题:

unsigned int day;
unsigned int month;
unsigned int year;

unsigned int hour;
unsigned int mins;
unsigned int seconds;


time_t conv(void)
{
   time_t retval=0;
   struct tm tm;
   tm.tm_mday=day;
   tm.tm_mon=month -1;
   tm.tm_year=year - 1900;
   tm.tm_hour=hour;
   tm.tm_min=mins;
   tm.tm_sec=seconds;
   tm.tm_isdst=-1;
   retval=mktime(&tm);
   return retval;
}

int main()
{
   time_t start=0;
   time_t end=0;
   time_t diff=0;
   // assign day, month, year ... for date1
   start=conv();
   // assign day, month, year ... for date2
   end=conv();
   if(start>end)
     diff=start - end;
   else
     diff=end - start;
   printf("seconds difference = %ld\n", diff);
   return 0; 
}

答案 1 :(得分:1)

您正在获得下溢。试试这个(无论变量是signed还是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;

答案 2 :(得分:1)

更改

time_diff_secs = time1_secs - time2_secs;

time_diff_secs = abs(time1_secs - time2_secs) % 86400;

这将强制它成为两次之间的最小时差,即使您在time_diff_secs计算中添加天,月等,也会有效。