C program to get the current UTC time

Here, we are going to learn how to get the current UTC time in C programming language?
Submitted by Nidhi, on July 22, 2021

Getting the current UTC time

To get the current UTC time in C, you can use the gmtime() function which is defined in time.h header file.

gmtime() Function

The gmtime() function is a library function which is defined in <time.h> header file, it is used to get the current Coordinated Universal Time (UTC) time.

Syntax

tm* gmtime ( const time_t* current_time );

Return value

It returns a structure tm that contains the below given declaration,

struct tm {
    int tm_sec; // seconds (from 0 to 59)
    int tm_min; // minutes (from 0 to 59)
    int tm_hour; // hours (from 0 to 23)
    int tm_mday; // day of the month
    int tm_mon; // month (from 0 to 11)
    int tm_year; // year (number of years since 1990)
    int tm_wday; // day of the week (from 0 to 6)
    int tm_yday; // day in the year (from 0 to 365)
    int tm_isdst; // daylight saving time
};

Here, we will write a C program to get the current UTC time.

C program to get the current UTC time

The source code to get the current UTC time is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to get current UTC time

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

int main()
{
    time_t tmi;
    struct tm* utcTime;

    time(&tmi);
    utcTime = gmtime(&tmi);

    printf("UTC Time: %2d:%02d:%02d\n", (utcTime->tm_hour) % 24, utcTime->tm_min, utcTime->tm_sec);
    printf("Time in India: %2d:%02d:%02d\n", (utcTime->tm_hour + 5) % 24, utcTime->tm_min, utcTime->tm_sec);

    return (0);
}

Output

UTC Time: 22:10:23
Time in India:  3:10:23

Explanation

Here, we created a tmi variable of structure time_t and initialize tmi time using time() function. Then we get the current UTC time using the gmtime() function. After that, we printed UTC time and time in india on the console screen.

C Advance Programs »

Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.