【问题标题】:How do you create a UTC time in C for a specific day, month and year?如何在 C 中为特定的日、月和年创建 UTC 时间?
【发布时间】:2010-11-11 00:34:55
【问题描述】:

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

2038 年 7 月 1 日

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

【问题讨论】:

  • 这不是一个糟糕的编程问题,如果您忽略特定的、在 32 位中无效的给定日期。我可能会将其拆分为两个问题,或者重写问题文本以突出显示 2038 问题。
  • 由于time_t类型是实现定义的,所以2038年只有32位系统有问题;大多数 64 位系统已经迁移到 64 位 time_t 值,您可能需要担心太阳会在此之前燃烧。 (具体来说:Solaris 10 - 64 位代码有sizeof(time_t) == 8,32 位代码有sizeof(time_t) == 4。)

标签: c date utc year2038


【解决方案1】:

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

【讨论】:

  • 为了清楚说明 2038 年 7 月超出范围,它会在 2038 年 1 月的某个时间翻转。
  • 2038 年 1 月 19 日 03:14:07 UTC 是翻转前的最后一秒。
  • 如果有人想知道,那是 1970 年 1 月 1 日午夜之后的 2^31-1 秒(即最大可能的 32 位有符号整数)。
【解决方案2】:

其他人注意到,您作为示例给出的特定日期超出了 32 位 time_t 可表示的最大日期/时间,通常称为Year 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;
}

【讨论】:

    【解决方案3】:

    你可以试试,使用下面的例子:

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

    它应该会给你预期的结果。

    【讨论】:

    • -1 没有按照 David 的要求做(忽略翻转方面)。 t = time(NULL) 获取当前时间,而不是任意时间。 -1 以令人困惑的方式重用变量(本地)。
    猜你喜欢
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 2020-10-21
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    相关资源
    最近更新 更多