【问题标题】:time function in CC中的时间函数
【发布时间】:2012-07-23 23:27:33
【问题描述】:

在 shell 脚本中,当我想要本地时间时,我会做类似的事情

date +%s

从命令行返回当前日期和时间,格式为“1343221713”

我想知道是否有办法在 C 中实现相同的结果

【问题讨论】:

    标签: c datetime time


    【解决方案1】:

    time(3) 更灵活的是gettimeofday(3)sys/time.h 中声明

    #include <sys/time.h>
    #include <stdio.h>
    int main(void)
    {
            struct timeval tv = {0};
            gettimeofday(&tv, NULL);
            printf("seconds since epoch %ld, microseconds %ld\n", tv.tv_sec, tv.tv_usec);
            return 0;
    }
    

    【讨论】:

      【解决方案2】:

      在 C 中使用 time.h 库

      示例:

      #include <stdio.h>
      #include <time.h>
      
      int main()
      {
          /* Obtain current time as seconds elapsed since the Epoch. */
          time_t clock = time(NULL);
      
          /* Convert to local time format and print to stdout. */
          printf("Current time is %s", ctime(&clock));
          return 0;
      }
      

      查看更多示例: http://en.wikipedia.org/wiki/C_date_and_time_functions

      【讨论】:

        猜你喜欢
        • 2011-07-11
        • 2015-02-05
        • 1970-01-01
        • 2012-08-13
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 2021-12-23
        • 2018-05-11
        相关资源
        最近更新 更多