繁体   English   中英

以秒为单位获取当前时间

[英]get the current time in seconds

我想知道是否有任何函数可以以秒为单位返回当前时间,仅为2位数秒? 我正在使用gcc 4.4.2。

以下完整程序将向您展示如何访问秒值:

#include <stdio.h>
#include <time.h>

int main (int argc, char *argv[]) {
    time_t now;
    struct tm *tm;

    now = time(0);
    if ((tm = localtime (&now)) == NULL) {
        printf ("Error extracting time stuff\n");
        return 1;
    }

    printf ("%04d-%02d-%02d %02d:%02d:%02d\n",
        tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
        tm->tm_hour, tm->tm_min, tm->tm_sec);

    return 0;
}

它输出:

2010-02-11 15:58:29

它的工作原理如下。

  • 它调用time()来获得当前时间的最佳近似值(通常是自纪元以来的秒数,但标准并未实际规定)。
  • 然后它调用localtime()将其转换为包含各个日期和时间字段的结构。
  • 在这一点上,您可以取消引用结构以获取您感兴趣的字段(在您的情况下为tm_sec但我已经展示了其中的一些)。

请记住,如果你想要格林威治时间,你也可以使用gmtime()而不是localtime() ,或者那些太年轻的人不能记住:-)。

一种更便携的方法是将当前时间作为time_t结构:

time_t mytime = time((time_t*)0);

检索此time_tstruct tm

struct tm *mytm = localtime(&mytime);

检查tm_sec成员mytm 根据您的C库,不能保证time()的返回值基于自分钟开始以来的秒数。

您可以使用gettimeofday (C11), time (Linux)或localtime_r (POSIX)获取当前时间; 取决于您感兴趣的日历和纪元。 您可以将其转换为日历纪元之后经过的秒数,或当前分钟的秒数,以您所使用的为准:

#include <stdio.h>
#include <string.h>
#include <time.h>

int main() {
    time_t current_secs = time(NULL);
    localtime_r(&current_secs, &current_time);

    char secstr[128] = {};
    struct tm current_time;
    strftime(secstr, sizeof secstr, "%S", &current_time);

    fprintf(stdout, "The second: %s\n", secstr);
    return 0;
}

你想使用gettimeofday:

男人2 gettimeofday

#include <stdio.h>
#include <sys/time.h>

int main (int argc, char **argv)
{
  int iRet;
  struct timeval tv;

  iRet = gettimeofday (&tv, NULL); // timezone structure is obsolete
  if (iRet == 0)
  {
    printf ("Seconds/USeconds since epoch: %d/%d\n",
            (int)tv.tv_sec, (int)tv.tv_usec);
    return 0;
  }
  else
  {
    perror ("gettimeofday");
  }

  return iRet;
}

这比使用time(0)更好,因为你也可以获得原子般的useconds,这是更常见的用例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM