日期比较函数
我的结构为:
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"}};
我想要做的是按stored.dates 对“stored”结构进行排序。
qsort(structs, 9, sizeof(struct stored*), sortdates); // sortdates function
我不太确定什么是排序这些日子的好方法?将它们与 C 字符串进行比较?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会使用以下方法将日期转换为数字:
然后进行简单的数字比较(对于月份,您需要从 Jan 映射到 1、Feb 到 2 等)。
如果您正在进行大量比较,您可能希望在结构中缓存等效的数字。
I would convert the dates to numbers using something like:
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.
如果将日期转换为
YYYYMMDD
格式(如20100314
),则可以将它们作为字符串或整数(转换后)进行比较。If you convert the dates to the format
YYYYMMDD
(as in20100314
), you can compare them as a string or as an integer (after conversion).ISO 8601 格式的日期(“YYYYMMDD”或“YYYY-MM-DD”等)与 C 字符串非常相似。您的格式不是 - 可以选择更改日期字符串的格式吗?
PS:如果去掉“-”,您甚至可以将日期存储为普通的 32 位整数。根据您的应用程序对这些日期的处理方式,这可能是额外的好处。
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.
您不能将它们作为字符串进行比较,但可以比较子字符串。比较一下年份,如果不相等,你就有答案了。接下来比较月份,您将需要某种表格来按名称对月份进行排序。最后,如果月份相同,则比较日期。
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.