From 0a2abb2b31f270ffeb9d4cb8adfdb07a86a5247c Mon Sep 17 00:00:00 2001 From: Anna Schumaker Date: Wed, 28 Oct 2015 03:55:40 -0400 Subject: [PATCH] core/string: Add string_tm2str() function to get a date stringg Signed-off-by: Anna Schumaker --- core/string.c | 7 +++++++ include/core/string.h | 3 +++ tests/core/string.c | 23 +++++++++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/core/string.c b/core/string.c index d159ea66..286a4576 100644 --- a/core/string.c +++ b/core/string.c @@ -39,6 +39,13 @@ gchar *string_sec2str_long(unsigned int sec) return res; } +gchar *string_tm2str(struct tm *tm) +{ + gchar *buf = g_malloc(20 * sizeof(gchar)); + strftime(buf, 20, "%Ex", tm); + return buf; +} + static gunichar __string_get_char(const gchar *str, const gchar *cur, const gchar *res) { diff --git a/include/core/string.h b/include/core/string.h index f97828d3..7c3f6ef6 100644 --- a/include/core/string.h +++ b/include/core/string.h @@ -17,6 +17,9 @@ gchar *string_sec2str(unsigned int); /* Convert number of seconds into a long-form time string. */ gchar *string_sec2str_long(unsigned int); +/* Convert a struct tm to a locale-dependant date string. */ +gchar *string_tm2str(struct tm *); + /* Convert the input string to lowercase, dropping special characters. */ gchar *string_lowercase(const gchar *); diff --git a/tests/core/string.c b/tests/core/string.c index 0a26152e..11ee5d24 100644 --- a/tests/core/string.c +++ b/tests/core/string.c @@ -4,6 +4,7 @@ */ #include #include +#include #define str_test_equal(lhs, rhs) \ test_strings_equal(lhs, g_strdup(rhs), __LINE__) @@ -53,6 +54,27 @@ void test_sec2str_long() "22 days, 4 hours, 12 minutes, 32 seconds"); } +void test_date() +{ + struct tm tm = { + .tm_year = 92, + .tm_mon = 9, + .tm_mday = 5, + }; + gchar *str; + + setlocale(LC_TIME, "C"); + str = string_tm2str(&tm); + test_equal(str, "10/05/92"); + g_free(str); + + setlocale(LC_TIME, "en_US"); + str = string_tm2str(&tm); + test_equal(str, "10/05/1992"); + g_free(str); + +} + void test_lowercase() { str_test_equal(string_lowercase(""), ""); @@ -82,6 +104,7 @@ void test_compare() DECLARE_UNIT_TESTS( UNIT_TEST("Seconds to String", test_sec2str), UNIT_TEST("Seconds to String (Long)", test_sec2str_long), + UNIT_TEST("Date to String", test_date), UNIT_TEST("String Lowercase", test_lowercase), UNIT_TEST("String Comparison", test_compare), );