【问题标题】:How to check if the actual time is between a time-range in string format [closed]如何检查实际时间是否在字符串格式的时间范围之间[关闭]
【发布时间】:2020-02-04 16:27:36
【问题描述】:

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

  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,我不完全理解。

谁能帮我解决一些实用的问题?

【问题讨论】:

  • 到目前为止您尝试了哪些方法,您遇到了哪些问题?您可以提供什么格式来提供您想要比较的实际时间?你能把它转换成与日期和时间相同的格式吗?

标签: c time struct compare


【解决方案1】:

这是一个例子:

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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多