w3resource

C Exercises: Convert a time_t object to calendar time expressed as Coordinated Universal Time


6. time_t to UTC Calendar Time

Write a program in C to convert a time_t object to calendar time expressed as Coordinated Universal Time.

Sample Solution:

C Code:

#define __STDC_WANT_LIB_EXT1__ 1 // Macro definition to request C11 library features
#include <stdio.h>
#include <time.h>

int main(void) {
    time_t t = time(NULL); // Get the current calendar time

    // Print the calendar time expressed as Coordinated Universal Time (UTC) and local time
    printf("\nThe calendar time expressed as Coordinated Universal Time is :");
    printf("\nUTC:   %s", asctime(gmtime(&t))); // Convert and print UTC time using gmtime() and asctime()
    printf("local: %s\n", asctime(localtime(&t))); // Convert and print local time using localtime() and asctime()

#ifdef __STDC_LIB_EXT1__
    struct tm buf;
    char str[26];

    // Convert UTC time using gmtime_s() and asctime_s(), and print the formatted string
    asctime_s(str, sizeof str, gmtime_s(&t, &buf));
    printf("UTC:   %s", str);

    // Convert local time using localtime_s() and asctime_s(), and print the formatted string
    asctime_s(str, sizeof str, localtime_s(&t, &buf));
    printf("local: %s", str);
#endif

    return 0;
}

Output:

The calendar time expressed as Coordinated Universal Time is :
UTC:   Thu Aug 03 10:53:03 2017
local: Thu Aug 03 16:23:03 2017

N.B.: The result may varry for your current system date and time.

Flowchart:

Flowchart: Convert a time_t object to calendar time expressed as Coordinated Universal Time


For more Practice: Solve these Related Problems:

  • Write a C program to convert a time_t object to UTC calendar time and print the result with a "UTC:" prefix.
  • Write a C program that displays a time_t object in UTC and also shows the corresponding local time for comparison.
  • Write a C program to convert a time_t object to UTC and output a custom formatted string that includes the full date and time.
  • Write a C program to display both UTC and local time by converting a time_t object, highlighting the time zone difference.

C Programming Code Editor:



Previous: Write a program in C to convert a tm object to custom wide string textual representation.
Next: Write a program in C to convert a time_t object to calendar time expressed as local time.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.