diff --git a/core/date.c b/core/date.c index dde33e6a..aed10f01 100644 --- a/core/date.c +++ b/core/date.c @@ -16,3 +16,14 @@ void date_today(struct date *date) date->d_day = now->tm_mday; } } + +int date_compare(const struct date *lhs, const struct date *rhs) +{ + int ret = lhs->d_year - rhs->d_year; + if (ret != 0) + return ret; + ret = lhs->d_month - rhs->d_month; + if (ret != 0) + return ret; + return lhs->d_day - rhs->d_day; +} diff --git a/core/tags/track.cpp b/core/tags/track.cpp index b7e2489e..fcd228e2 100644 --- a/core/tags/track.cpp +++ b/core/tags/track.cpp @@ -104,13 +104,7 @@ void Track :: played() int Track :: compare_date(const Track *rhs) { - int ret = _date.d_year - rhs->_date.d_year; - if (ret == 0) { - ret = _date.d_month - rhs->_date.d_month; - if (ret == 0) - ret = _date.d_day - rhs->_date.d_day; - } - return ret; + return date_compare(&_date, &rhs->_date); } void Track :: read(file &file) diff --git a/include/core/date.h b/include/core/date.h index 1afec771..ca5286ba 100644 --- a/include/core/date.h +++ b/include/core/date.h @@ -14,4 +14,13 @@ struct date { /* Set the provided date structure to today's date. */ void date_today(struct date *); +/* + * Compare two dates. + * + * if ret < 0: lhs < rhs. + * if ret = 0: lhs == rhs. + * if ret > 0: lhs > rhs. + */ +int date_compare(const struct date *, const struct date *); + #endif /* OCARINA_CORE_DATE_H */ diff --git a/tests/core/date.c b/tests/core/date.c index 076b0966..8a48a36f 100644 --- a/tests/core/date.c +++ b/tests/core/date.c @@ -25,6 +25,36 @@ void test_date() test_equal(date.d_day, today->tm_mday); } +void test_compare() +{ + struct date a = { + .d_year = 2015, + .d_month = 6, + .d_day = 17, + }; + struct date b = { + .d_year = 2010, + .d_month = 12, + .d_day = 10, + }; + + /* Check year comparison. */ + test_equal(date_compare(&a, &b), 5); + test_equal(date_compare(&b, &a), -5); + + /* Check month comparison. */ + b.d_year = a.d_year; + test_equal(date_compare(&a, &b), -6); + test_equal(date_compare(&b, &a), 6); + + /* Check day comparison. */ + b.d_month = a.d_month; + test_equal(date_compare(&a, &a), 0); + test_equal(date_compare(&a, &b), 7); + test_equal(date_compare(&b, &a), -7); +} + DECLARE_UNIT_TESTS( UNIT_TEST("Date", test_date), + UNIT_TEST("Date Comparison", test_compare), );