检查当前时间(无日期)是C之间的两次

时间:2016-10-24 12:52:50

标签: c time

你能帮我在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:00off_time = 01:00:00(午夜后的第二天)。我想检查current time : 19:27:00是否介于on和off_time之间。 On和off_time是字符串。

由于

2 个答案:

答案 0 :(得分:0)

我会使用sscanf将char缓冲区转换为int,然后比较那些

示例:

int on_hour, on_minute, on_second;
int off_hour, off_minute, off_second;

sscanf(on_timestr, "%d:%d:%d", &on_hour, &on_minute, &on_second);
sscanf(off_timestr, "%d:%d:%d", &off_hour, &off_minute, &off_second);

if (on_hour < off_hour)
//do your compare logic

或者:

#include <time.h>

tm on_time, off_time;

sscanf(on_time, "%d:%d:%d", &on_time.tm_hour, &on_time.tm__min, &on_time.tm_sec);
sscanf(off_time, "%d:%d:%d", &off_time.tm_hour, &off_time.tm__min, &off_time.tm_sec);

答案 1 :(得分:0)

最短的比较解决方案包括将所有字符串时间戳转换为time_t值。

  

改善来源,Brian McFarland建议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
}