Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

GLib Date and Time Functions: Create, Convert, Format, and Calculate with GDateTime

A practical guide to GLib’s GDateTime, GTimeZone, and GTimeSpan APIs, including construction, timezone conversion, formatting, ownership, and calendar-versus-duration arithmetic.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use GDateTime for date-and-time values in GLib, GTimeZone to control their timezone, and GTimeSpan for elapsed durations. The key distinction is whether you mean a calendar change—such as “the same local time tomorrow”—or a fixed duration such as exactly 24 hours. Those can produce different results around daylight-saving transitions.

What GLib’s date and time types represent

GDateTime is an opaque, immutable, reference-counted value combining a Gregorian date and time. It supports microsecond precision and dates from 0001-01-01 00:00:00 through 9999-12-31 23:59:59.999999. Its time model follows POSIX semantics and does not represent leap seconds.

As an Amazon Associate I earn from qualifying purchases.

GTimeZone represents a timezone, while GTimeSpan represents a signed interval in microseconds. Keep the distinction clear: a timezone says how an instant is shown on a clock; a time span measures a duration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create a GDateTime

Choose a constructor based on whether you have a current time, calendar fields, Unix seconds, or ISO 8601 text:

  • For the current instant, use g_date_time_new_now(tz) with a timezone, or the convenience functions g_date_time_new_now_local() and g_date_time_new_now_utc().
  • For explicit calendar fields, use g_date_time_new(tz, ...), g_date_time_new_local(...), or g_date_time_new_utc(...).
  • For Unix seconds, use g_date_time_new_from_unix_local() or g_date_time_new_from_unix_utc().
  • For ISO 8601 input, use g_date_time_new_from_iso8601().

For example, this creates a value for the current local time and formats it as ISO 8601:

GDateTime *now = g_date_time_new_now_local();
gchar *text = g_date_time_format_iso8601(now);

/* Use text. */
g_free(text);
g_date_time_unref(now);

Constructors can fail and return NULL if the requested date or time is invalid or outside the supported range. Check returned values before using them. The timeval-based constructors have been deprecated since GLib 2.62; prefer the Unix-time APIs instead.

Choose the right timezone

Construct a value in the zone that matches the meaning of the input. Use local time when the value is specifically tied to the machine’s local settings, UTC for a universal clock representation, or an explicit timezone when the relevant civil time belongs to a named region. To create a regional zone, pass an identifier such as Europe/London to g_time_zone_new(). An abbreviation for an offset or interval is not a valid timezone identifier for that function.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To display the same instant in another zone, use g_date_time_to_timezone(); the convenience conversions are g_date_time_to_local() and g_date_time_to_utc(). These return a new GDateTime for the same instant, represented in the destination zone. They do not change the original value.

Convert to and from Unix time

g_date_time_new_from_unix_utc() and g_date_time_new_from_unix_local() create a date-time from Unix seconds, interpreted in UTC or local time respectively. In the other direction, g_date_time_to_unix() returns whole Unix seconds, rounded down. If the fractional part matters, do not assume that this whole-second result preserves microseconds: newer GLib documentation also lists APIs for microsecond Unix-time conversion, so check the API available in the GLib release you target.

GTimeSpan values use microseconds. For example, G_TIME_SPAN_SECOND is 1,000,000 microseconds; related constants express milliseconds, minutes, hours, and days in the same unit. Use these constants instead of treating a span as a count of seconds.

Add calendar time or elapsed time?

GLib provides g_date_time_add() for a span and calendar-oriented helpers including g_date_time_add_days(), g_date_time_add_weeks(), g_date_time_add_months(), g_date_time_add_years(), plus hour, minute, and second variants. Select the operation that matches the requirement:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Need Use Meaning and edge case
A fixed elapsed duration g_date_time_add() with a GTimeSpan Adds the specified duration. A 24-hour duration is not always the same as the next local calendar day across daylight-saving changes.
A later calendar date g_date_time_add_days() or another calendar helper Advances the calendar field. A local day that crosses a daylight-saving transition can span 23 or 25 elapsed hours.
Month-based recurrence g_date_time_add_months() Month arithmetic is not associative: adding two months to January 31 yields March 31, while adding one month twice can yield March 28 or 29.

For elapsed differences, use g_date_time_difference(), which returns a GTimeSpan. For ordering or equality, use g_date_time_compare() or g_date_time_equal().

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Format output or parse ISO 8601

Use g_date_time_format_iso8601() when you need ISO 8601 text containing the date, time, and timezone. For custom display, g_date_time_format() accepts a documented subset of C99 strftime() directives, selected GNU extensions (%k, %l, %s, P, and modifiers), and Python’s %f for fractional seconds.

Formatted output is UTF-8. Month names and other locale-sensitive text can vary with the locale, so use ISO 8601 output rather than localized display strings when you need a stable interchange representation. To read ISO 8601 input, use g_date_time_new_from_iso8601().

Handle ownership and failed operations

GDateTime values cannot be edited in place. Arithmetic and timezone conversions produce new values, leaving the source unchanged. Treat returned values as owned references: release them with g_date_time_unref() when finished. If another owner needs to retain a value, acquire a reference with g_date_time_ref().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Most operations that produce a date-time can fail with NULL if the result would be outside the supported range. Check results after construction, arithmetic, and conversion before dereferencing or formatting them.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.