如何在 Linux 中C++中将日期和时间字符串精确到毫秒?
How to get date and time string accurate to milliseconds in C++ in Linux?
我希望能够以毫秒分辨率将本地时间和日期放入字符串中,如下所示:
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';
}
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 通过字符串来计算长度需要更长的时间,而不是移动字符串几次?
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- 如何将时间字符串 (M:SS) 转换为浮点数
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- 时间持续时间到时间字符串
- 如何将我的每个矢量字符串转换为纪元时间日期
- 如何找到修改后的字符串与原始字符串相等的时间
- 在C++中修改字符串的BigO时间复杂度是多少
- 格式化的时间字符串在解析为time_point时会产生小时差异
- 使用 ctime 保存新时间点会覆盖旧字符串?
- 将日期字符串转换为 unix 时间戳
- 有序地图字符串搜索与整数搜索之间的时间复杂度
- 字符串连接时间复杂度 c++
- 提升,从字符串问题中获得时间
- C 将字符串时间戳转换为STD :: Chrono :: System_Clock :: Time_point
- 将字符串时间转换为UNIX时间戳
- 最接近地图的字符串/时间戳