tags:

views:

499

answers:

3

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

+5  A: 

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
Just to make it clear July 2038 is out of range, it rolls over sometime in January 2038.
R. Bemrose
2038 January 19, 03:14:07 UTC being the last second before it rolls over.
R. Bemrose
In case anyone's wondering, that's 2^31-1 seconds (i.e. the largest possible 32-bit signed integer) after midnight on January 1, 1970.
Aric TenEyck
A: 

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.

Roopesh Majeti
-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
+2  A: 

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