日期比较函数

发布于 2024-08-25 08:55:46 字数 494 浏览 7 评论 0原文

我的结构为:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

淡看悲欢离合 2024-09-01 08:55:46

我会使用以下方法将日期转换为数字:

year * 10000 + month * 100 + day;

然后进行简单的数字比较(对于月份,您需要从 Jan 映射到 1、Feb 到 2 等)。

如果您正在进行大量比较,您可能希望在结构中缓存等效的数字。

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.

っ〆星空下的拥抱 2024-09-01 08:55:46

如果将日期转换为 YYYYMMDD 格式(如 20100314),则可以将它们作为字符串或整数(转换后)进行比较。

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).

天涯离梦残月幽梦 2024-09-01 08:55:46

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.

满地尘埃落定 2024-09-01 08:55:46

您不能将它们作为字符串进行比较,但可以比较子字符串。比较一下年份,如果不相等,你就有答案了。接下来比较月份,您将需要某种表格来按名称对月份进行排序。最后,如果月份相同,则比较日期。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文