Georgi Makedonski Georgi Makedonski - 1 month ago 9
C Question

Check current time (without date) is between two times in C

Can you help me to implement this in 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))


I have
on_time = 18:00:00
and
off_time = 01:00:00
(next day after midnight). I want to check if
current time : 19:27:00
is between on and off_time. On and off_time are strings.

Thanks

Answer

A shortest comparison solution consists to convert all string-timestamp to time_t value.

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

And your comparison is:

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
}