c - 从 C 中的时间和日期字符串值中获取毫秒差

标签 c time c-libraries

我在变量中分别有两个日期和时间字符串。我需要以毫秒为单位计算这两个日期和时间值之间的差异。如何在 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 type time_t. If the calendar time cannot be represented, the function returns the value (time_t)(-1). C11dr §7.27.2.3 4

The difftime function returns the difference expressed in seconds as a double §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/

相关文章:

c++ - 使用宏替代功能

c - 如何判断哪些 libxml2 函数返回需要释放的对象?

c - 文件处理: unusual error reading file

c - 使用指针时类型不兼容

c - 为什么这些调用具有相同的内存地址?

java - 在java中生成随机双数的最快方法

javascript - 如何在 javascript 中将字符串转换为 Unix 时间戳?

java - 查找用户输入的当前日期和时间之间的差异

c - 自动生成自定义C库的头文件