1

如何在 C 中为以下日期创建 UTC 时间:

2038 年 7 月 1 日

使用标准 ANSI C 函数调用(假设结构的tm_year元素tm不能大于 137)?

4

3 回答 3

6

你没有。32 位 ANSI C time_t 在 2038 年翻转。这就像问您如何在旧的 2 位数年份 COBOL 系统中创建 2003 年 7 月 23 日。

于 2009-07-15T14:10:27.233 回答
2

其他人注意到,您作为示例给出的特定日期超出了 32 位 time_t 可表示的最大日期/时间,通常称为2038 年问题。一种解决方案是使用 64 位 time_t,某些 64 位 POSIX 系统(linux amd64)会这样做,然后调用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;
}
于 2009-07-15T15:45:39.893 回答
0

您可以尝试使用以下示例:

#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;
}

它应该给你预期的结果。

于 2009-07-15T14:20:08.733 回答