我在变量中分别有两个日期和时间字符串。我需要以毫秒为单位计算这两个日期和时间值之间的差异。如何在 C 中获得它。该解决方案应该跨平台工作(至少是 Windows 和 Unix)。
char date1[] = {"26/11/2015"};
char time1[] = {"20:22:19"};
char date2[] = {"26/11/2015"};
char time2[] = {"20:23:19"};
首先我需要将其保存到某个时间结构中,然后比较 2 个时间结构以获得差异。 C 库中可用的时间结构是什么?
最佳答案
使用mktime()
和difftime()
The
mktime
function returns the specified calendar time encoded as a value of typetime_t
. If the calendar time cannot be represented, the function returns the value(time_t)(-1)
. C11dr §7.27.2.3 4The
difftime
function returns the difference expressed in seconds as adouble
§7.27.2.2 2
#include <time.h>
#include <stdlib.h>
#include <string.h>
time_t parse_dt(const char *mdy, const char *hms) {
struct tm tm;
memset(&tm, 0, sizeof tm);
if (3 != sscanf(mdy, "%d/%d/%d", &tm.tm_mon, &tm.tm_mday, &tm.tm_year)) return -1;
tm.tm_year -= 1900;
tm.tm_mday++;
if (3 != sscanf(hms, "%d:%d:%d", &tm.tm_hour, &tm.tm_min, &tm.tm_sec)) return -1;
tm.tm_isdst = -1; // Assume local time
return mktime(&tm);
}
int main() {
// application
char date1[] = { "26/11/2015" };
char time1[] = { "20:22:19" };
char date2[] = { "26/11/2015" };
char time2[] = { "20:23:19" };
time_t t1 = parse_dt(date1, time1);
time_t t2 = parse_dt(date2, time2);
if (t1 == -1 || t2 == -1) return 1;
printf("Time difference %.3f\n", difftime(t2, t1) * 1000.0);
return 0;
}
输出
Time difference 60000.000
关于c - 从 C 中的时间和日期字符串值中获取毫秒差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33941661/