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

Problem Solution:

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 );

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.

Program:

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

ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.