【发布时间】:2017-08-07 19:14:21
【问题描述】:
我希望能够以毫秒分辨率将本地时间和日期放入字符串中,如下所示:
YYYY-MM-DD hh:mm:ss.sss
似乎是一件简单的事情,但我还没有找到一个简单的答案来说明如何做到这一点。我正在用 C++ 编写,并且可以访问 11 个编译器,但如果 C 解决方案更干净,我可以使用它。我在这里找到了一个带有解决方案Get both date and time in milliseconds 的帖子,但考虑到使用标准库,它肯定不会那么困难。我可能会继续使用这种类型的解决方案,但希望通过在 SO 上提出问题来增加知识库。
我知道这会奏效,但似乎又是不必要的困难:
#include <sys/time.h>
#include <stdio.h>
int main(void)
{
string sTimestamp;
char acTimestamp[256];
struct timeval tv;
struct tm *tm;
gettimeofday(&tv, NULL);
tm = localtime(&tv.tv_sec);
sprintf(acTimestamp, "%04d-%02d-%02d %02d:%02d:%02d.%03d\n",
tm->tm_year + 1900,
tm->tm_mon + 1,
tm->tm_mday,
tm->tm_hour,
tm->tm_min,
tm->tm_sec,
(int) (tv.tv_usec / 1000)
);
sTimestamp = acTimestamp;
cout << sTimestamp << endl;
return 0;
}
尝试查看 C++ 的 put_time 和旧 C 方式的 strftime。两者都只能让我达到我能说的最好的第二个分辨率。你可以在下面看到我到目前为止得到的两种方法。我想把它放到一个字符串中
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::cout << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << std::endl;
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,sizeof(buffer),"%Y-%m-%d %I:%M:%S",timeinfo);
std::string str(buffer);
std::cout << str;
我唯一能想到的是使用 gettimeofday 并删除除最后一秒以外的所有数据并将其附加到时间戳,仍然希望有一种更清洁的方法。
有人找到更好的解决方案吗?
【问题讨论】:
-
你看过
<chrono>吗? -
@RichardCritten 我不会认为这是该特定问题的重复,因为这是关于 C 的问题,因此不会有任何提供时间实用程序的 C++ 库。
-
我需要当地时间,会更新问题
-
我想不出比附加毫秒数不同的方法。对于使用
<chrono>的方法,有这个旧答案:stackoverflow.com/questions/31281293/…