如何在 Linux 中C++中将日期和时间字符串精确到毫秒?

How to get date and time string accurate to milliseconds in C++ in Linux?

本文关键字:字符串 时间 Linux C++ 日期      更新时间:2023-10-16

我希望能够以毫秒分辨率将本地时间和日期放入字符串中,如下所示:

YYYY-MM-DD hh:mm:ss.sss

似乎是一件简单的事情,但我还没有找到如何做到这一点的简单答案。 我正在用C++编写,并且确实可以访问 11 个编译器,但如果它更干净,使用 C 解决方案可以。 我在这里找到了一个带有解决方案的帖子 以毫秒为单位获取日期和时间,但考虑到使用标准库,这肯定不会那么困难。 我可能会继续使用这种类型的解决方案,但希望通过在 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.%03dn",
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;
}

尝试查看put_time以获取C++和旧 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 并删除除最后一秒以外的所有数据并将其附加到时间戳中,仍然希望有一种更干净的方法。

有人找到更好的解决方案吗?

我建议看看Howard Hinnant的日期库。wiki 中给出的示例之一显示了如何获取当前本地时间,达到给定的std::chrono::system_clock实现精度(Linux 上的纳秒,从内存中?

编辑:正如霍华德在评论中指出的那样,您可以使用date::floor()来获得所需的精度。因此,要按照问题中的要求生成字符串,您可以执行以下操作:

#include "tz.h"
#include <iostream>
#include <string>
#include <sstream>
std::string current_time()
{
const auto now_ms = date::floor<std::chrono::milliseconds>(std::chrono::system_clock::now());
std::stringstream ss;
ss << date::make_zoned(date::current_zone(), now_ms);
return ss.str();
}
int main()
{
std::cout << current_time() << 'n';
}