首页 > 解决方案 > 如何检查实际时间是否在字符串格式的时间范围之间

问题描述

我在树莓派上使用 C 并尝试执行以下操作:在 .txt 文件中有 2 个时间和 2 个日期(在 4 个不同的行中)。我要检查实际时间是否在这些日期时间之间。所以在 CI 中有:

  1. Data.time1 (Char) 包含:00:00:00
  2. Data.time2 (Char) 包含:23:59:59
  3. Data.date1 (Char) 包含:1970-01-01
  4. Data.date2 (Char) 包含:1970-01-01
  5. Timenow (int) 包含当前时间的 Unix 值

我尝试了很多选择,但我想我不得不使用struct tm,我不完全理解。

任何人都可以帮我解决一些实用的问题吗?

标签: ctimestructcompare

解决方案


这是一个例子:

void example(char *t1, char *d1, char *t2, char *d2)
{
    // t= "23:59:59"
    // d= "1970-01-01"
    struct tm from, to;
    time_t t_from, t_to, t_now;

    from.tm_year= atoi(d1)-1900;    // Year (current year minus 1900)
    from.tm_mon=  atoi(d1+5)-1;     // Month (0–11; January = 0)
    from.tm_mday= atoi(d1+8);       // Day of month (1–31)
    from.tm_hour= atoi(t1);         // Hours since midnight (0–23)
    from.tm_min=  atoi(t1+3);       // Minutes after hour (0–59)
    from.tm_sec=  atoi(t1+6);       // Seconds after minute (0–59)
    t_from= mktime(&from);          // now it is a numeric value

    to.tm_year= atoi(d2)-1900;      // Year (current year minus 1900)
    to.tm_mon=  atoi(d2+5)-1;       // Month (0–11; January = 0)
    to.tm_mday= atoi(d2+8);         // Day of month (1–31)
    to.tm_hour= atoi(t2);           // Hours since midnight (0–23)
    to.tm_min=  atoi(t2+3);         // Minutes after hour (0–59)
    to.tm_sec=  atoi(t2+6);         // Seconds after minute (0–59)
    t_to= mktime(&to);

    t_now= time(0);

    printf("%s\n",asctime(&from));
    printf("%s\n",asctime(&to));
    printf("%s\n",ctime(&t_now));

    if (t_from <= t_now && t_now <= t_to)
        printf("yes\n");
    else
        printf("no\n");
}

推荐阅读