我有两个ISO 8601格式的日期:
20170423T221118.585Z
20170423T221119.583Z
在使用核心语言库的Linux in C中,如何计算这两个日期之间的毫秒差异?
答案 0 :(得分:4)
使用核心C语言执行以下操作:
#include <stdio.h>
#include <time.h>
double subtract_dates(const char *start_date_time, const char *end_date_time);
void create_tm(time_t *ret_time, const char* date_time, int *ret_time_ms);
int main(int argc, char *argv[])
{
const char *start_date_time = "20170423T221118.585Z";
const char *end_date_time = "20170423T221119.583Z";
double msdiff;
msdiff = subtract_dates(end_date_time, start_date_time);
printf("Date/time difference(ms) = %f\n", msdiff);
}
double subtract_dates(const char *end_date_time, const char *start_date_time )
{
time_t ret_start_date_time;
time_t ret_end_date_time;
double diff_s;
int start_time_ms;
int end_time_ms;
double diff_ms;
create_tm(&ret_start_date_time, start_date_time, &start_time_ms);
create_tm(&ret_end_date_time, end_date_time, &end_time_ms);
diff_s = difftime(ret_end_date_time, ret_start_date_time);
// convert to milliseconds
diff_ms = (diff_s * 1000) + (end_time_ms - start_time_ms);
return diff_ms;
}
void create_tm(time_t *ret_time, const char* date_time, int *ret_time_ms)
{
struct tm time;
time_t otherTime;
int y,M,d,h,m,s;
int ms;
sscanf(date_time, "%4d%2d%2dT%2d%2d%2d.%3dZ", &y, &M, &d, &h, &m, &s, &ms);
time.tm_year = y - 1900; // Year since 1900
time.tm_mon = M - 1; // 0-11
time.tm_mday = d; // 1-31
time.tm_hour = h; // 0-23
time.tm_min = m; // 0-59
time.tm_sec = s; // 0-61 (0-60 in C++11)
time.tm_isdst = -1; // let mktime check for DST
*ret_time = mktime(&time);
*ret_time_ms = ms;
}
这将为您提供以下输出:
日期/时差(ms)= 998.000000