【问题标题】:how to deduce current time (Clock) from unix gettime Jan 1970 API?如何从 unix gettime Jan 1970 API 推断当前时间(时钟)?
【发布时间】:2013-05-13 16:19:41
【问题描述】:

我正在使用time() 函数,它返回自 1970 年 1 月以来经过的秒数; 我想推断当前时间和日期,这是我所看到的..

   #define SECONDS_PER_YEAR  31536000u
   #define SECONDS_PER_MONTH 2628288u
    #define SECONDS_PER_WEEK  604800u

...

       time_t unaccountedSeconds = time(NULL);

        // Calculate years
          int years = unaccountedSeconds / SECONDS_PER_YEAR;
           // Seconds not absorbed by years
                    unaccountedSeconds = unaccountedSeconds % SECONDS_PER_YEAR;

      // Calculate months
           int months = unaccountedSeconds / SECONDS_PER_MONTH;
                 // Seconds not absorbed by months
         unaccountedSeconds = unaccountedSeconds % SECONDS_PER_MONTH;

              // Calculate weeks

这对我不起作用。

【问题讨论】:

  • 如果所有月份的长度相同,那应该可以。但他们不是。 (就此而言,也不是所有年份。)
  • 提示:除以 4 年的秒数。在您尝试计算月/日之前,将剩余部分转换为当天的天数和秒数。

标签: c time


【解决方案1】:

我建议你使用 localtime(3) 函数。这会为您分解,并为您提供一个填充的 struct tm。

【讨论】:

    【解决方案2】:

    试试这个:

    time_t now = time(NULL);
    struct tm* tmTime = localtime(&now);
    
    int years = tmTime.tm_year;
    int months = tmTime.tm_mon;
    int wDay = tmTime.tm_wday; // day of the week
    // ...
    

    【讨论】:

      【解决方案3】:

      人-一次

      man -a asctime

      man -a 当地时间

      result = time(NULL);
      printf("current time %s  its %ju secs since the Epoch\n", 
                   asctime(localtime(&result)), (uintmax_t)result);
      return(0);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-14
        • 1970-01-01
        • 2019-07-13
        • 2019-05-01
        相关资源
        最近更新 更多