【问题标题】:find difference between times in c在c中找到时间之间的差异
【发布时间】:2015-02-19 17:27:29
【问题描述】:

我有 2 个时间字符串,想找出它们之间的区别。我的代码有效。但是当我尝试相同的值时,它会显示不同的输出。这是我的代码:

    #include <time.h>
    #include <stdio.h>
    time_t convtotime(char *time_detail,char *format){
        struct tm tm;
        strptime(time_detail,format,&tm);
        time_t t = mktime(&tm);
        return t;

    }
    int main(int argc, char const *argv[])
    {
        char buff[25];
        time_t newtime = convtotime("12/Dec/2014:10:44:19","%d/%b/%Y:%H:%M:%S");
        time_t oldtime = convtotime("12/Dec/2014:10:44:35","%d/%b/%Y:%H:%M:%S");
        printf("%lf",difftime(oldtime,newtime));
    }

它输出:

3616.000000

16.000000

【问题讨论】:

  • 你的意思是当你再次运行这个确切的程序时得到不同的结果?

标签: c datetime time


【解决方案1】:

manual for strptime 说:

这个函数原则上不初始化tm,只存储 指定的值。 这意味着tm应该在之前初始化 通话

那就试试吧:

struct tm tm = {0};
strptime(time_detail, format, &tm);

the standard 中的措辞也很有趣:

未指定是否多次调用 strptime() 使用相同的 tm 结构将更新结构的当前内容或 覆盖结构的所有内容。

【讨论】:

  • 所以观察到的一小时偏移是由于 tm 的夏令时成员包含一些随机值。好收获!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-13
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多