如何在c中找到两次之间的差异?

时间:2009-05-15 05:49:37

标签: c++ c

我的第一次是12:10:20 PM,第二次是7:10:20同一天我怎么能找到差异呢?

我的想法是将所有时间转换为秒,并找到差异再次转换为时间

Approch还不错吗?

3 个答案:

答案 0 :(得分:12)

您需要difftime功能。

修改

如果你没有difftime可用,我会建议你从你所处的任何格式转换到纪元的秒数​​,进行计算并转换回你需要的任何格式。以下功能组可以帮助您完成所有这些转换:

asctime, ctime, gmtime, localtime, mktime, asctime_r, ctime_r, gmtime_r, localtime_r - transform date and time to broken-down time or ASCII

timegm, timelocal - inverses for gmtime and localtime ( may not be available on all systems )

答案 1 :(得分:7)

不一定是最好的方法,但如果你想使用系统上的可用内容,difftime()和mktime()可以提供帮助 -

#include <time.h>

tm Time1 = { 0 };  // Make sure everything is initialized to start with.
/* 12:10:20 */
Time1.tm_hour = 12;
Time1.tm_min = 10;
Time1.tm_sec = 20;

/* Give the function a sane date to work with (01/01/2000, here). */
Time1.tm_mday = 1;
Time1.tm_mon = 0;
Time1.tm_year = 100;

tm Time2 = Time1;  // Base Time2 on Time1, to get the same date...
/* 07:10:20 */
Time2.tm_hour = 7;
Time2.tm_min = 10;
Time2.tm_sec = 20;

/* Convert to time_t. */
time_t TimeT1 = mktime( &Time1 );
time_t TimeT2 = mktime( &Time2 );

/* Use difftime() to find the difference, in seconds. */
double Diff = difftime( TimeT1, TimeT2 );

答案 2 :(得分:0)

你的方法听起来很合理。

再进一步,您将转换为通用时间格式,例如Unix time,然后采取差异。