c - 如何检查实际时间是否在字符串格式的时间范围之间
问题描述
我在树莓派上使用 C 并尝试执行以下操作:在 .txt 文件中有 2 个时间和 2 个日期(在 4 个不同的行中)。我要检查实际时间是否在这些日期时间之间。所以在 CI 中有:
- Data.time1 (Char) 包含:00:00:00
- Data.time2 (Char) 包含:23:59:59
- Data.date1 (Char) 包含:1970-01-01
- Data.date2 (Char) 包含:1970-01-01
- Timenow (int) 包含当前时间的 Unix 值
我尝试了很多选择,但我想我不得不使用struct tm
,我不完全理解。
任何人都可以帮我解决一些实用的问题吗?
解决方案
这是一个例子:
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");
}
推荐阅读
- c# - NodeJS 和 Serialport – 读取 RFID 卡
- windows - Windows Mobile 6.1 编程
- latex - Latex:表枚举
- terraform - “列表”参数的值无效:列表元素类型不正确:需要字符串
- python - Pandas groupby cumsum 从最后到第一个
- r-package - R中cox回归的变量选择
- vim - 如何在vim中将行剪切到剪贴板?不是拉扯或复制,而是切割
- typescript - 使用 Angular Native 和 Firebase 更新配置文件
- tensorflow - Tensorflow:使用 Conv2D 层,但忽略某些像素进行梯度计算
- ajaxform - Ajax 请求一直显示“此请求没有负载”