Blarsssss
Blarsssss

Reputation: 101

Comparing two dates as char arrays in C

Bear with my guys this is my second stackoverflow question, please point me in the right direction if I'm doing this wrong

I have two dates as chars.

I print out the dates:

printf("%s - %s\n",tmpPtr->date, currentDate);

And I have an if statement which is always executed

if(tmpPtr->date != currentDate) {       // perhaps strcmp(), don't know
  printf("Dates are not equal\n");
}

But this cannot be true because these are my results:

27/12/2015 - 27/12/2015
Dates are not equal
27/12/2015 - 27/12/2015
Dates are not equal
28/12/2015 - 27/12/2015
Dates are not equal
29/12/2015 - 28/12/2015
Dates are not equal
29/12/2015 - 29/12/2015
Dates are not equal
29/12/2015 - 29/12/2015
Dates are not equal
30/12/2015 - 29/12/2015
Dates are not equal
31/12/2015 - 30/12/2015
Dates are not equal
31/12/2015 - 31/12/2015
Dates are not equal

This can't be true because some dates are equal?

Am I comparing the strings correctly? Is it just comparing the memory allocation or something of the sort?

Upvotes: 2

Views: 1789

Answers (2)

vitaut
vitaut

Reputation: 55564

If dates are in the same format which seems to be the case, then use strcmp. Otherwise parse them and compare year, month and date of one string to corresponding fields of the other.

Upvotes: 0

Marievi
Marievi

Reputation: 5011

In order to compare strings, use strcmp() like this :

if (strcmp(tmpPtr->date,currentDate) != 0) {      
    printf("Dates are not equal\n");
}

Upvotes: 4

Related Questions