gmtime Function in C

The gmtime function in C converts the calendar time pointed to by the timer into a broken-down time, expressed as UTC. That means it uses the value of the time_t object to fill a tm structure with the values that represent the corresponding time, expressed in Coordinated Universal Time (UTC) or GMT timezone.

 

Syntax of gmtime:

The prototype of the gmtime() function is below:

#include <time.h>

struct tm *gmtime(const time_t *timer);

 

Parameters:

The gmtime function takes one parameter.

timer = Pointer to a time_t object to convert.

 

Returns:

The gmtime functions return a pointer to the broken-down time, or a null pointer if the specified time cannot be converted to UTC. That means,

On Success:  The gmtime() function returns a pointer to a tm object.
On Failure:  A null pointer is returned.

Note: In gmtime() result is stored in static storage.

 

Example Program:

The below code explains how the gmtime() function works in C.

#include <stdio.h>
#include <time.h>

int main()
{
    // object
    time_t current_time;

    // use time function
    time(&current_time);

    // call gmtime()
    struct tm* ptime = gmtime(&current_time);

    printf("UTC: %2d:%02d:%02d\n",
           ptime->tm_hour, ptime->tm_min, ptime->tm_sec);

    return 0;
}

Output:

UTC: 16:01:58

 

How does the above code work?

In the above code, created one time_t objects to store the times. When the program starts execution, the time() function stores the current time in the current_time variable.

// object
time_t current_time;

// use time function
time(&current_time);

 

Now in the last call, the gmtime() function store the broken-down time into a pointer to the tm object.

// call gmtime()

struct tm* ptime = gmtime(&current_time);

 

Recommended Post: