C programming - standard library
The "time.h" header file in C programming provides functions for working with date and time values. Some of the commonly used functions in "time.h" include:
"time": Returns the current calendar time as the number of seconds since the Epoch (January 1, 1970).
"gmtime": Converts a time value to a broken-down time structure in Coordinated Universal Time (UTC).
"localtime": Converts a time value to a broken-down time structure in the local time zone.
"asctime": Converts a broken-down time structure to a string in a format like "Sun Sep 16 01:03:52 2018\n".
"ctime": Converts a time value to a string in a format like "Sun Sep 16 01:03:52 2018\n".
"difftime": Computes the difference between two time values in seconds.
"mktime": Converts a broken-down time structure to a time value.
Here is an example of using the "time.h" header file in a C program:
reref to:theitroad.com#include <stdio.h>
#include <time.h>
int main() {
time_t t = time(NULL);
// print the current calendar time
printf("Current time: %s", ctime(&t));
// convert the current time to UTC
struct tm *utc_time = gmtime(&t);
printf("UTC time: %s", asctime(utc_time));
// convert the current time to the local time zone
struct tm *local_time = localtime(&t);
printf("Local time: %s", asctime(local_time));
// compute the difference between two times
time_t t2 = time(NULL);
double diff = difftime(t2, t);
printf("Difference in seconds: %f\n", diff);
// convert a broken-down time structure to a time value
struct tm tstruct = {
.tm_sec = 30,
.tm_min = 10,
.tm_hour = 5,
.tm_mday = 10,
.tm_mon = 8,
.tm_year = 121,
.tm_wday = 3,
.tm_yday = 0,
.tm_isdst = -1
};
time_t t3 = mktime(&tstruct);
printf("Time value for 10:10:30 AM on September 10, 2021: %ld\n", (long)t3);
return 0;
}
In this example, the "time.h" header file functions are used to work with date and time values. The "time" function is used to get the current calendar time as a time value. The "gmtime" and "localtime" functions are used to convert the current time to a broken-down time structure in Coordinated Universal Time (UTC) and the local time zone, respectively. The "asctime" and "ctime" functions are used to convert a time value and a broken-down time structure to strings. The "difftime" function is used to compute the difference between two time values. Finally, the "mktime" function is used to convert a broken-down time structure to a time value. The output of the program will vary based on the current time, but an example output could be:
Current time: Sun Feb 27 23:44:33 2022 UTC time: Mon Feb 28 04:44:33 2022 Local time: Sun Feb 27 23:44:33 2022 Difference in seconds: 17.000000 Time value for 10:10:
