繁体   English   中英

如何在 C 中找到当前日期和未来日期之间的天数时差?

[英]How can I find the time difference in days between the current date and a future date in C?

我正在尝试查找当前日期和给定的未来日期之间的天数。 从我目前所读的内容来看,我可以使用内置的日期类型struct tm ,这就是我尝试过的,但我就是无法让它工作。 每次我使用它时,我都会得到一些像-1615574208.000000这样的垃圾。 我将给出我尝试过的众多示例之一。 在这里,我试图在午夜找到今天和明天之间的时差。

#include <stdio.h>
#include <time.h>

int main() {
    time_t t = time(NULL);
    struct tm current_date = *localtime(&t);    // get the current date information
    struct tm away_date;

    // now we set the away date information
    away_date.tm_year = 2021;
    away_date.tm_mon = 3;
    away_date.tm_mday = 13;
    away_date.tm_hour = 23;
    away_date.tm_min = 59;
    away_date.tm_sec = 59;

    // now we make both of these of type time_t so we can use difftime()
    time_t t1, t2;
    t2 = mktime(&away_date);
    t1 = mktime(&current_date);

    // now we find the difference
    double diff = difftime(t2, t1);
    printf("%f\n", diff);

    return 0;
}

正如我所说,这行不通。 当我运行它时,我得到-1615574757.000000 显然有什么问题,但我不知道是什么。 我一直在搜索并尝试上述代码的各种版本,但我无法让它工作。

这不是垃圾,它是自 UNIX 纪元 - 1970 年(约 51 年)开始以来的秒数。

t2可能为零,因为您将tm_year设置为超出范围 3921 (1900+2021)。 除了由其数据类型强加的限制之外,对tm_year没有定义的限制,但在具有 32 位time_t的系统上,2038 年 1 月 19 日实际上是 time 的结束

在声明 function 不起作用之前,请务必查看输入 - 垃圾输入,垃圾输出。 以及tm_year是从 1900 年开始的偏移量,请注意tm_mon从 1 月 == 0 开始,因此您的away_date是在 4 月,这也可能不是您所期望的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM