diff options
author | Philip Withnall <withnall@endlessm.com> | 2019-07-26 13:39:07 +0100 |
---|---|---|
committer | Philip Withnall <withnall@endlessm.com> | 2019-07-29 12:27:29 +0100 |
commit | dbabd2b8a745bfed4890f2d6cbd7d7848bc4f034 (patch) | |
tree | fdb5e878493a972a9996863c0bae863c657d84c4 /glib/gdatetime.c | |
parent | 8f385b8cf595279c8b9d56e6b0c6cad9186ccb15 (diff) | |
download | glib-dbabd2b8a745bfed4890f2d6cbd7d7848bc4f034.tar.gz |
gdatetime: Add g_date_time_format_iso8601() convenience function
This is a simple wrapper around g_date_time_format_iso8601() which
always produces ISO 8601 dates, without people having to remember the
format string for them (and with the convenience of terminating UTC
dates with āZā rather than ā+00ā).
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1438
Diffstat (limited to 'glib/gdatetime.c')
-rw-r--r-- | glib/gdatetime.c | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/glib/gdatetime.c b/glib/gdatetime.c index c286954c4..5b09c1854 100644 --- a/glib/gdatetime.c +++ b/glib/gdatetime.c @@ -3393,6 +3393,49 @@ g_date_time_format (GDateTime *datetime, return g_string_free (outstr, FALSE); } +/** + * g_date_time_format_iso8601: + * @datetime: A #GDateTime + * + * Format @datetime in [ISO 8601 format](https://en.wikipedia.org/wiki/ISO_8601), + * including the date, time and time zone, and return that as a UTF-8 encoded + * string. + * + * Returns: a newly allocated string formatted in ISO 8601 format + * or %NULL in the case that there was an error. The string + * should be freed with g_free(). + * Since: 2.62 + */ +gchar * +g_date_time_format_iso8601 (GDateTime *datetime) +{ + GString *outstr = NULL; + gchar *main_date = NULL; + gint64 offset; + + /* Main date and time. */ + main_date = g_date_time_format (datetime, "%Y-%m-%dT%H:%M:%S"); + outstr = g_string_new (main_date); + g_free (main_date); + + /* Timezone. Format it as `%:::z` unless the offset is zero, in which case + * we can simply use `Z`. */ + offset = g_date_time_get_utc_offset (datetime); + + if (offset == 0) + { + g_string_append_c (outstr, 'Z'); + } + else + { + gchar *time_zone = g_date_time_format (datetime, "%:::z"); + g_string_append (outstr, time_zone); + g_free (time_zone); + } + + return g_string_free (outstr, FALSE); +} + /* Epilogue {{{1 */ /* vim:set foldmethod=marker: */ |