tags:

views:

61

answers:

4

I have struct as:

struct stored
{
    char *dates; // 12/May/2010, 10/Jun/2010 etc..
};
// const
struct stored structs[] = {{"12/May/2010"}, {"12/May/2011"}, 
                           {"21/May/2009"}, {"13/May/2011"}, 
                           {"10/May/2011"}, {"19/May/2011"}};

What I want to do is to sort struct 'stored' by stored.dates.

qsort(structs, 9, sizeof(struct stored*), sortdates); // sortdates function

I'm not quite sure what would be a good way to sort those days? Compare them as c-strings?

A: 

You can't compare these as strings, but you can compare substrings. Compare the years, and if they aren't equal you have your answer. Next compare the months, you'll need some kind of table to order the months by name. Finally if the months are the same, compare the days.

Mark Ransom
+1  A: 

I would convert the dates to numbers using something like:

year * 10000 + month * 100 + day;

and then do a simple numeric comparison (and for month, you'll need to map from Jan to 1, Feb to 2, etc.).

If you're doing a lot of comparisons, you may want to cache the numeric equivalent in the structure.

R Samuel Klatchko
+1  A: 

If you convert the dates to the format YYYYMMDD (as in 20100314), you can compare them as a string or as an integer (after conversion).

bta
+1  A: 

ISO 8601 formatted dates ("YYYYMMDD" or "YYYY-MM-DD" etc.) are trivially comparable as C strings. Your format is not - would changing the format of the date strings be an option?

PS: If you get rid of the "-", you could even store the date as plain 32bit integer. Depending on what your application does with those dates, that might be an additional bonus.

DevSolar
yes, changing it to YYYY-MM-DD is definitely a possibility.
Chris
This has the nice side effect that the ISO 8601 notation is both international (no English month names) *and* the only unambiguous numerical notation (that I know of). I would go for it.
DevSolar