如何获得两次之间的时差(24h格式)

时间:2017-10-01 22:07:31

标签: c

我目前正在尝试创建一个程序,其中用户给出两个值(时间,hh:mm:ss)并获得两次之间的差异。如果只使用12h格式,这是有效的;但是,必须使用24小时格式。

我当前的时间结构如下所示:

typedef struct time {
    int hours;
    int minutes;
    int seconds;
} time;

我目前计算差异的函数如下:

time calculateTimeDiff(time time1, time time2) {
    time timeResult;

    timeResult.hours = time1.hours - time2.hours;

    if(time1.minutes != 00 && time2.minutes != 00) {
            timeResult.minutes = time1.minutes - time2.minutes;
    }
    else {
            timeResult.minutes = 00;
    }

    if(time1.seconds != 00 && time2.seconds != 00) {
            timeResult.seconds = time1.seconds - time2.seconds;
    }
    else {
            timeResult.seconds = 00;
    }

    while(timeResult.seconds > 60) {
        timeResult.seconds -= 60;
        timeResult.minutes += 1;
    }

    while(timeResult.minutes > 60) {
        timeResult.minutes -= 60;
        timeResult.hours += 1;
    }

    return timeResult;
}

我支持24小时格式的尝试是,如果小时“超过”12小时格式,则增加12小时,并将时间除以2(在黑暗中离完整镜头不远,只是为了看看哪些有效,哪些无效。但是,这只会导致结果不正确。

赞赏所有答案!

1 个答案:

答案 0 :(得分:2)

  

如何获得两次(24h格式)之间的时差

尽管代码可以在OP的代码中使用许多if-then-else,但将h:m:s时间转换为秒,减去并转换回h:m:s会很简单。所以我建议重写:

typedef struct time {
    int hours;
    int minutes;
    int seconds;
} time;

long time_sec(time t) {
  return (t.hours * 60L + t.minutes)*60 + t.seconds;
}

time sec_time(long s) {
  time t;
  t.hours = s / 3600;
  s %= 3600;
  t.minutes = s / 60;
  t.seconds = s %= 60;
  return t;
}

time calculateTimeDiff(time time1, time time2) {
  long t1 = time_sec(time1);
  long t2 = time_sec(time2);
  long diff = t1 - t2;
  return sec_time(diff);
}

#include <stdio.h>
void test(time t1, time t2) {
  printf("t1: %3d:%3d:%3d,    ", t1.hours, t1. minutes, t1.seconds);
  printf("t2: %3d:%3d:%3d,    ", t2.hours, t2. minutes, t2.seconds);
  time t3 = calculateTimeDiff(t1, t2);
  printf("t1-t2: %3d:%3d:%3d,   ", t3.hours, t3. minutes, t3.seconds);
  t3 = calculateTimeDiff(t2, t1);
  printf("t2-t1: %3d:%3d:%3d\n", t3.hours, t3. minutes, t3.seconds);
}

int main(void) {
  test((time){14,00,00}, (time){13,00,00});
  test((time){22,00,00}, (time){04,00,00});
}

输出

t1:  14:  0:  0,    t2:  13:  0:  0,    t1-t2:   1:  0:  0,   t2-t1:  -1:  0:  0
t1:  22:  0:  0,    t2:   4:  0:  0,    t1-t2:  18:  0:  0,   t2-t1: -18:  0:  0

请注意,差异可能会导致time中返回的calculateTimeDiff()成员的值为负值。