gmtime() Function Example in C Programming

In this source code example, we will see how to use the gmtime() function in C programming with an example.

gmtime() Function Overview

The gmtime() function in C converts a given time in time_t format into a structure representing Coordinated Universal Time (UTC) or Greenwich Mean Time (GMT). This structure, named struct tm, breaks down the time into details such as year, month, day, hour, minute, and second. The function can be found in the time.h library. 

Key Points: 

- time.h header is needed to make use of gmtime()

- It accepts a pointer to a time_t object as its argument. 

- The function returns a pointer to a struct tm, providing the UTC representation of the given time. 

- It's especially useful when you need a standardized time format, irrespective of the system's local time settings.

Source Code Example

#include <stdio.h>
#include <time.h>  // Necessary for gmtime(), time(), and struct tm

int main() {
    time_t current_time;
    struct tm *utc_time_info;

    // Capture the current calendar time
    time(&current_time);

    // Convert the current time to UTC format
    utc_time_info = gmtime(&current_time);

    printf("The current UTC time is: %d-%d-%d %02d:%02d:%02d\n",
           utc_time_info->tm_year + 1900,     // Years are counted from 1900
           utc_time_info->tm_mon + 1,         // Months range from 0 (January) to 11 (December)
           utc_time_info->tm_mday,            // Day of the month
           utc_time_info->tm_hour,
           utc_time_info->tm_min,
           utc_time_info->tm_sec);

    return 0;
}

Output

The current UTC time is: YYYY-MM-DD HH:MM:SS

Explanation

1. First, we include the required header files: stdio.h for input/output procedures and time.h for gmtime(), time(), and the definition of struct tm.

2. Within main(), we initially retrieve the current calendar time in the format of time_t.

3. The gmtime() function is then employed to turn this time_t value into a UTC structure.

4. We access the fields of the structure, such as tm_year, tm_mon, etc., to print the detailed date and time. Remember that certain adjustments are required, e.g., adding 1900 to the year or adding 1 to the month, due to the structure's representation.

Using the gmtime() function is crucial when dealing with systems or applications where a consistent and universal time format is necessary, regardless of the locality or time zone of the system.


Comments