diff --git a/lib/utils/mu-utils.cc b/lib/utils/mu-utils.cc index 881a499f..e641450d 100644 --- a/lib/utils/mu-utils.cc +++ b/lib/utils/mu-utils.cc @@ -242,6 +242,37 @@ Mu::date_to_time_t_string(int64_t t) return buf; } +std::string +Mu::time_to_string(const std::string& frm, time_t t, bool utc) +{ + GDateTime* dt = [&] { + if (utc) + return g_date_time_new_from_unix_utc(t); + else + return g_date_time_new_from_unix_local(t); + }(); + + char* str = g_date_time_format(dt, frm.c_str()); + g_date_time_unref(dt); + if (!str) { + g_warning("failed to format time"); + return {}; + } + + /* ensure it's utf8 */ + char* utf8_str = g_locale_to_utf8(str, -1, NULL, NULL, NULL); + g_free(str); + if (!utf8_str) { + g_warning("failed to convert date to utf8"); + return {}; + } + + std::string res{utf8_str}; + g_free(utf8_str); + + return res; +} + static std::string delta_ymwdhMs(const std::string& expr) { diff --git a/lib/utils/mu-utils.hh b/lib/utils/mu-utils.hh index e8c7f2b5..d1ed7e59 100644 --- a/lib/utils/mu-utils.hh +++ b/lib/utils/mu-utils.hh @@ -129,6 +129,19 @@ std::string date_to_time_t_string(const std::string& date, bool first); */ std::string date_to_time_t_string(int64_t t); +/** + * Get a string for a given time_t and format + * memory that must be freed after use. + * + * @param frm the format of the string (in strftime(3) format) + * @param t the time as time_t + * @param utc whether to display as UTC(if true) or local time + * + * @return a string representation of the time in UTF8-format, or empty in case + * of error. + */ +std::string time_to_string(const std::string& frm, time_t t, bool utc = false) G_GNUC_CONST; + /** * Create a std::string by consuming a gchar* array; this takes ownership * of str which should no longer be used.