Comparing chars....?

Hi,

I’m a bit stuck with this an wondered if someone might be able to lend me a hand?

I have two char strings which represent time in this format… date:hour:minute:second - so “07:19:10:00”

How would I compare these two strings to see which is sooner in terms of time?

So:

char* time="07:19:10:00"
char* now="07:19:21:16"

if (time < now)

Would I need to convert these to another data type first?

Thanks for any pointers :slight_smile:

Here you will get away with a character-by-character comparison as lexicographical order will match time order. Start at the left hand end of the string, stop when there's a mismatch - the larger digit at that point will be part of the string with the later timestamp value.

Convert the timestrings to standard unix time, that is seconds since 1 jan 1970 represented in a unsigned long. longs are easily compared.

Think the time library contains conversion code .

You could convert them to a long…

or as MarkT said… you could match from left to right…

byte diff ;
byte index ;
for (index=0; index < 11; index++) // look at each character of the time strings
{
    diff = time[index] - now[index] ;
    if (diff != 0)
         break ; // stop at the first difference
}
if (diff == 0) // there where no differences
{
     // times are the same
}
else if (diff < 0) // the first difference was now[index] > time[index]
{
     // now > time
}
else if (diff > 0) // the first difference was now[index] < time[index]
{
     // now < time
}

Fantastic, thanks folks - much appreciated.

Makes good sense and thanks for the code example dafid.

I am now having problems with the way I am constructing my 'time' string.... from 4 vars using sprintf but I don't competely understand the syntax and I'm getting odd output? Any idea what I need to change to get the output from the code below to = "07:19:10:00"

So:

int date = 07
int hour = 19
int minute = 10
int second = 00

sprintf(time,"%02d_%02d_%02d_20%02d.dat",date, hour, minute, second);

strcmp would be easier, no?

Hi Magician,

strcmp sounds good - how does that work?

Got sprintf working too :-)... should have been: sprintf(time,"%02d:%02d:%02d:%02d",date, hour, minute, second);

Thanks.