计算C中的时间差

标签 c time standard-library

我尝试使用 <time.h>库,但它看起来像 <time.h>并不真正支持时间追溯到 1900 年之前,也可能超过某个 x 年。

我的问题是:

  1. 我可以使用<time.h>吗?计算时间差(以秒、小时或天为单位),例如:

    5 月 1 日 2744 年和 1 月 24 日 566 年

  2. 是否 <time.h>支持闰年吗?意思是如果我计算上面的差异 - 那会算闰年吗?我显然可以做出类似的东西:

    int toDays(struct tm *date)
    {
        int days = date->tm_yday;
        int year;
        for (year = 1; year < date->tm_year; ++year)
        {
            days += isLeapYear(year) ? 366 : 365;
        }
        return days;
    }
    

但话说回来 - tm_year从 1900 开始计算,对吗?

老实说,我对这种结构一无所知,我可能会自己写一个,除非有人能帮我解决这个问题。使用 <time.h> 是否有意义?当我想像问题 1 那样计算年份时?

最佳答案

你可以试试 difftime() 函数。

首先,您必须定义两个可以保存所需数据的结构,例如

struct tm start_date, end_date;

然后根据您的日期用数据填充结构。

然后使用difftime()作为

seconds = difftime(mktime(&end_date),mktime(&start_date))

以下示例将帮助您理解流程。

#include<stdio.h>
#include<time.h>
int main()
{
   time_t now;
   struct tm start_date, end_date;
   start_date = *localtime(&now);
   end_date = *localtime(&now);

   start_date.tm_year = 1013;
   end_date.tm_year = 1015;

   unsigned long int diff = difftime(mktime(&end_date), mktime(&start_date));
   printf("DIFF: [%lu]",diff);
   return(0);
}

关于计算C中的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33472775/

相关文章:

c++ - 如何将 C++ 标准库链接到 Monotouch 应用程序

c++ - 特化 std::make_shared

rust - 为什么 Read::read_to_string() 不返回字符串?

c - Scalapack中处理器子集的不相交网格及其通信

math - 由于重力问题,利用时间来提高速度(无法获得完美的弹性)

c - 如何在终端自动执行代码

具有不同日期和时间字段的日期/时间之间的 SQL 查询

C - 数据存储/访问

c - 链表添加节点更改所有节点值,而不仅仅是一个

c - 单线程模式下并行合并非常慢