你能帮我用 C 实现这个吗:
((on_time <= off_time and CURTIME() >= on_time and CURTIME() <= off_time) or
(off_time < on_time and (CURTIME() <= off_time or CURTIME() >= on_time))
我有 on_time = 18:00:00
和 off_time = 01:00:00
(第二天午夜后)。我想检查当前时间:19:27:00
是否在 on 和 off_time 之间。 on 和 off_time 是字符串。
谢谢
最佳答案
最短的比较解决方案是将所有字符串时间戳转换为 time_t 值。
Improving the source as Brian McFarland suggests
memset()
.
struct tm tmVar;
time_t t_on_time, t_off_time, t_curr_time;
memset(&tmVar, 0, sizeof(tmVar));
if(sscanf(on_time, "%d:%d:%d", &tmVar.tm_hour, &tmVar.tm_min, &tmVar.tm_sec)==3) {
t_on_time = mktime(&tmVar);
}
memset(&tmVar, 0, sizeof(tmVar));
if(sscanf(off_time, "%d:%d:%d", &tmVar.tm_hour, &tmVar.tm_min, &tmVar.tm_sec)==3) {
t_off_time = mktime(&tmVar);
}
memset(&tmVar, 0, sizeof(tmVar));
if(sscanf(CURTIME(), "%d:%d:%d", &tmVar.tm_hour, &tmVar.tm_min, &tmVar.tm_sec)==3) {
t_curr_time = mktime(&tmVar);
}
你的比较是:
if (((t_on_time <= t_off_time) && (t_curr_time >= t_on_time) && (t_curr_time <= t_off_time)) ||
((t_off_time < t_on_time) && ((t_curr_time <= t_off_time) || (t_curr_time >= t_on_time))) {
// To do something
}
关于检查当前时间(不带日期)是否在 C 中的两个时间之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40218968/