0

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

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

4

3 回答 3

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; 
}
于 2013-12-03T16:18:09.983 回答
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;
于 2013-12-03T16:06:57.850 回答
1

改变

time_diff_secs = time1_secs - time2_secs;

time_diff_secs = abs(time1_secs - time2_secs) % 86400;

这将迫使它成为两个时间之间的最小时间差,并且即使您在time_diff_secs计算中添加天数、月数等也将起作用。

于 2013-12-03T16:07:01.017 回答