gdatetime: Format iso8601 strings with microsecond precision

This commit is contained in:
Johan Bjäreholt 2020-08-05 13:36:19 +02:00
parent bcb48a18e3
commit 8e13683f70
2 changed files with 17 additions and 1 deletions

View File

@ -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 * including the date, time and time zone, and return that as a UTF-8 encoded
* string. * string.
* *
* Since GLib 2.66, this will output to sub-second precision if needed.
*
* Returns: (transfer full) (nullable): a newly allocated string formatted in * 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 * ISO 8601 format or %NULL in the case that there was an error. The string
* should be freed with g_free(). * should be freed with g_free().
@ -3477,9 +3479,15 @@ g_date_time_format_iso8601 (GDateTime *datetime)
GString *outstr = NULL; GString *outstr = NULL;
gchar *main_date = NULL; gchar *main_date = NULL;
gint64 offset; 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 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); outstr = g_string_new (main_date);
g_free (main_date); g_free (main_date);

View File

@ -2208,6 +2208,14 @@ test_format_iso8601 (void)
g_free (p); g_free (p);
g_date_time_unref (dt); g_date_time_unref (dt);
g_time_zone_unref (tz); 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 #pragma GCC diagnostic push