C Exercises: Convert a time_t object to calendar time expressed as local time
C Date Time: Exercise-7 with Solution
Write a program in C to convert a time_t object to calendar time expressed as local time.
Sample Solution:
C Code:
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <time.h>
int main(void)
{
// Get current time in seconds since epoch
time_t t = time(NULL);
// Print the calendar time expressed as local time and UTC time
printf("\nThe calendar time expressed as a local Time is :");
printf("\nUTC: %s", asctime(gmtime(&t))); // Convert and print UTC time
printf("local: %s\n", asctime(localtime(&t))); // Convert and print local time
#ifdef __STDC_LIB_EXT1__
// Using secure versions of functions available in C11
struct tm buf;
char str[26];
// Convert and print UTC time using secure version of functions
asctime_s(str, sizeof str, gmtime_s(&t, &buf));
printf("UTC: %s", str);
// Convert and print local time using secure version of functions
asctime_s(str, sizeof str, localtime_s(&t, &buf));
printf("local: %s", str);
#endif
}
Sample Output:
The calendar time expressed as a local Time is : UTC: Thu Aug 03 11:15:59 2017 local: Thu Aug 03 16:45:59 2017
N.B.: The result may varry for your current system date and time.
Flowchart:
C Programming Code Editor:
Previous: Write a program in C to convert a time_t object to calendar time expressed as Coordinated Universal Time.
Next: Write a program in C to print the date and time before 24 months.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/c-programming-exercises/datetime/c-datetime-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics