【问题标题】:Getting timestamp with date and time including microseconds获取带有日期和时间的时间戳,包括微秒
【发布时间】:2016-11-22 08:11:08
【问题描述】:

对于错误日志,我想创建一个带有日期和时间的时间戳,包括微秒。它的格式应该是 2016.07.19 13:59:31:123.456

找了很多time_t的例子,但是分辨率只有几秒……

【问题讨论】:

标签: c windows time


【解决方案1】:

你可以使用gettimeofday:

#include <time.h>
#include <sys/time.h>
....
struct timeval tv;
gettimeofday(&tv, NULL);

其中struct timeval定义为:

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

然后您可以使用gmtime 分割秒部分:

struct tm *ts = gmtime(&tv.tv_sec);

其中struct tm定义为:

          struct tm {
              int tm_sec;         /* seconds */
              int tm_min;         /* minutes */
              int tm_hour;        /* hours */
              int tm_mday;        /* day of the month */
              int tm_mon;         /* month */
              int tm_year;        /* year */
              int tm_wday;        /* day of the week */
              int tm_yday;        /* day in the year */
              int tm_isdst;       /* daylight saving time */
          };

tm结构的成员有:

  • tm_sec 分钟后的秒数,通常取值范围为 0 到 59,但最多可以达到 60 以允许闰秒。

  • tm_min 小时后的分钟数,范围为 0 到 59。

  • tm_hour 午夜过后的小时数,范围为 0 到 23。

  • tm_mday 月份中的第几天,范围为 1 到 31。

  • tm_mon 自一月以来的月数,范围为 0 到 11。

  • tm_year 自 1900 年以来的年数。

  • tm_wday 自星期日以来的天数,范围为 0 到 6。

  • tm_yday 自 1 月 1 日以来的天数,范围为 0 到 365。

  • tm_isdst 指示夏令时是否有效的标志 在描述的时间。如果夏令时,该值为正 时间有效,如果没有,则为零,如果信息为负,则为负 化不可用。

编辑:

Windows 没有gettimeofday。这是您可以使用的实现:

int gettimeofday(struct timeval *tv, struct timezone *tz)
{
    const unsigned __int64 epoch_diff = 11644473600000000;
    unsigned __int64 tmp;
    FILETIME t;

    if (tv) {
        GetSystemTimeAsFileTime(&t);

        tmp = 0;
        tmp |= t.dwHighDateTime;
        tmp <<= 32;
        tmp |= t.dwLowDateTime;

        tmp /= 10;
        tmp -= epoch_diff;
        tv->tv_sec = (long)(tmp / 1000000);
        tv->tv_usec = (long)(tmp % 1000000);
    }

    return 0;
}

【讨论】:

  • “tm 结构的成员是:”描述了最小组成员。 C 规范使用“tm 结构应至少包含以下成员......”gettimeofday() 不是标准库函数。 C 确实有timespec_get(),但我不确定它是否受欢迎。
  • 感谢您的回复。
  • @nobody 很高兴我能帮上忙。如果您觉得有用,请随时 accept this answer
  • 对不起,我按下了 Enter 按钮,我的评论已经发送。我想写:谢谢你的回复。我正在使用 Windows 笔记本和 XC16 编译器。我没有 。我在哪里可以获得它以及如何安装它?
  • @nobody Windows 没有gettimeofday,但是我提供了一个您可以使用的实现。
猜你喜欢
  • 2013-06-22
  • 1970-01-01
  • 2020-04-30
  • 2016-09-23
  • 2017-12-01
  • 2017-07-24
  • 2015-09-28
  • 2012-09-17
  • 2016-06-22
相关资源
最近更新 更多