1

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

phuclv
  • 37,963
  • 15
  • 156
  • 475
David
  • 14,047
  • 24
  • 80
  • 101
  • It's not a bad programming question, if you ignore the specific, invalid in 32-bit, date given. I might split this into two questions, or rewrite the question text to highlight the 2038 problem. – jmanning2k Jul 15 '09 at 14:59
  • Since the `time_t` type is implementation-defined, it is only 32-bit systems that have a problem in year 2038; most 64-bit systems have already migrated to 64-bit `time_t` values, and you probably need to worry about the sun burning up before that rolls over. (Specifically: Solaris 10 - 64-bit code has `sizeof(time_t) == 8` and 32-bit code has `sizeof(time_t) == 4`.) – Jonathan Leffler Jul 16 '09 at 05:26

3 Answers3

6

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.

Aric TenEyck
  • 8,002
  • 1
  • 34
  • 48
2

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;
}
mctylr
  • 5,159
  • 20
  • 32
0

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.

ephemient
  • 198,619
  • 38
  • 280
  • 391
Roopesh Majeti
  • 556
  • 1
  • 11
  • 23
  • 1
    -1 Doesn't do what David asked about (ignoring the roll-over aspect). t = time(NULL) get the *current* time, not an arbitrary time. -1 for reusing a variable (local) in a confusing manner. – mctylr Jul 15 '09 at 15:18