Gmtime Function In C

The C function gmtime takes in a time parameter (in Coordinated Universal Time) and produces an object with attributes representing various time units (such as seconds, hours, days, etc.). It accepts a t_time type value, denoting the time in seconds, as input and converts it to the struct tm data structure.

Time elements in Coordinated Universal Time (UTC) or Greenwich Mean Time (GMT) can be saved in various struct tms. The <time.h> header file declares the C function gmtime.

Syntax:

It has the following syntax:

Example

struct tm *gmtime(const time_t *time);
  • tm_hour can be used to retrieve the hours.
  • tm_min can be used to retrieve the minutes.
  • tm_sec can be used to retrieve the seconds.
  • A pointer to a time_t object, which represents the calendar time, is contained in the time parameter.
  • The UTC time is represented by a struct tm object, to which the function returns a pointer.

The returned results are as follows:

-

  • Provides a reference to a tm object if successful.

-

  • Otherwise, a Null pointer is returned.
  • Pseudocode:

    Example
    
    function convertToUtc(time):
        // Declare a variable to store the converted time
        struct tm *timeinfo
        // Convert the time to UTC
        timeinfo = gmtime(time)
        // Return the UTC time
        return timeinfo
    

    Example 1:

Let's consider a scenario to demonstrate the functionality of the gmtime function in the C programming language.

Example

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

int main() {
    time_t raw_time;
    struct tm *time_info;
    time(&raw_time);
    time_info = gmtime(&raw_time);
    printf("Current UTC time and date: %s", asctime(time_info));
    return 0;
}

Output:

Output

[Program Output]

Example 2:

Let's consider another instance to demonstrate the gmtime function in the C programming language.

Example

#include <stdio.h>
#include <time.h>
#define CHINA_OFFSET (+8)
#define INDIA_OFFSET (+5)
int main()
{
    time_t current_time;
    struct tm* pt;
    current_time = time(NULL);
    pt = gmtime(¤t_time);
    printf("Current time:\n");
    printf("Beijing: %02d:%02d:%02d\n",
           (pt->tm_hour + CHINA_OFFSET) % 24, pt->tm_min, pt->tm_sec);
    printf("Delhi: %02d:%02d:%02d\n",
           (pt->tm_hour + INDIA_OFFSET) % 24, pt->tm_min, pt->tm_sec);
    return 0;
}

Output:

Output

[Program Output]

Conclusion:

  • The gmtime function always converts the time to UTC regardless of the system default time setting.
  • It is the main purpose of the gmtime function.

Input Required

This code uses input(). Please provide values below: