How do I create a UTC time in C for the following date:
1st July 2038
using standard ANSI C function calls (given that the tm_year element of the tm structure cannot be greater than 137) ?
How do I create a UTC time in C for the following date:
1st July 2038
using standard ANSI C function calls (given that the tm_year element of the tm structure cannot be greater than 137) ?
You don't. The 32-bit ANSI C time_t rolls over in 2038. It's like asking how you create July 23, 2003 in your old 2-digit-year COBOL system.
You can try, making use of the following example :
#include <time.h>
#include <stdio.h>
int main(void)
{
struct tm *local;
time_t t;
t = time(NULL);
local = localtime(&t);
printf("Local time and date: %s\n", asctime(local));
local = gmtime(&t);
printf("UTC time and date: %s\n", asctime(local));
return 0;
}
It should give you, the expected result.
Others have noted that the particular date you give as an example falls beyond the maximum date/time representable by a 32-bit time_t, often referred to as the Year 2038 problem. One solution is to use a 64-bit time_t, which some 64-bit POSIX systems do (linux amd64), and call mktime
.
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
struct tm future; /* as in future date */
time_t t;
future.tm_sec = 0;
future.tm_min = 0;
future.tm_hour = 0;
future.tm_mday = 1; /* 1st */
future.tm_mon = 6; /* July */
future.tm_year = 2038 - 1900; /* 2038 in years since 1900 */
future.tm_isdst = 0; /* Daylight Saving not in affect (UTC) */
#ifdef _BSD_SOURCE
future.tm_zone = "UTC";
#endif
t = mktime( &future );
if ( -1 == t ) {
printf("Error converting 1 July 2038 to time_t time since Epoch\n");
return EXIT_FAILURE;
}
printf("UTC time and date: %s\n", asctime( &future ) );
return EXIT_SUCCESS;
}