From 8e13683f70913e234aa89b4a46ccdc0c9432ccf6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johan=20Bj=C3=A4reholt?= Date: Wed, 5 Aug 2020 13:36:19 +0200 Subject: [PATCH] gdatetime: Format iso8601 strings with microsecond precision --- glib/gdatetime.c | 10 +++++++++- glib/tests/gdatetime.c | 8 ++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/glib/gdatetime.c b/glib/gdatetime.c index 143815b52..f85afab0c 100644 --- a/glib/gdatetime.c +++ b/glib/gdatetime.c @@ -3465,6 +3465,8 @@ g_date_time_format (GDateTime *datetime, * including the date, time and time zone, and return that as a UTF-8 encoded * string. * + * Since GLib 2.66, this will output to sub-second precision if needed. + * * Returns: (transfer full) (nullable): 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(). @@ -3477,9 +3479,15 @@ g_date_time_format_iso8601 (GDateTime *datetime) GString *outstr = NULL; gchar *main_date = NULL; gint64 offset; + gchar *format = "%Y-%m-%dT%H:%M:%S"; + + /* if datetime has sub-second non-zero values below the second precision we + * should print them as well */ + if (datetime->usec % G_TIME_SPAN_SECOND != 0) + format = "%Y-%m-%dT%H:%M:%S.%f"; /* Main date and time. */ - main_date = g_date_time_format (datetime, "%Y-%m-%dT%H:%M:%S"); + main_date = g_date_time_format (datetime, format); outstr = g_string_new (main_date); g_free (main_date); diff --git a/glib/tests/gdatetime.c b/glib/tests/gdatetime.c index 79a446e4b..3e75f4ed2 100644 --- a/glib/tests/gdatetime.c +++ b/glib/tests/gdatetime.c @@ -2208,6 +2208,14 @@ test_format_iso8601 (void) g_free (p); g_date_time_unref (dt); g_time_zone_unref (tz); + + tz = g_time_zone_new_utc (); + dt = g_date_time_new (tz, 2020, 8, 5, 12, 30, 55.000001); + p = g_date_time_format_iso8601 (dt); + g_assert_cmpstr (p, ==, "2020-08-05T12:30:55.000001Z"); + g_free (p); + g_date_time_unref (dt); + g_time_zone_unref (tz); } #pragma GCC diagnostic push