c++ - 如何在 Linux 中的 C++ 中获取精确到毫秒的日期和时间字符串?

标签 c++ linux date time

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

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 并删除除最后一秒以外的所有数据并将其附加到时间戳,仍然希望有一种更清洁的方法。

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

最佳答案

我建议查看 Howard Hinnant 的 date library . examples given in the 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';
} 

关于c++ - 如何在 Linux 中的 C++ 中获取精确到毫秒的日期和时间字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42837030/

相关文章:

c++ - 绘图时防止闪烁

c++ - QApplication::exec() 拒绝返回(在控制台程序中)

c++ - 将 makefile 转换为其相关的 makefile

c - 应用程序无缘无故地被杀死。怀疑 BSS 高。如何调试呢?

linux - 无需下载即可获取 Content-Disposition 文件名

javascript - 从 Google Calendar API 检索 "All Day"事件时,如何考虑时区偏移?

python - 当我使用Thrift将C++中的映射序列化到磁盘,然后使用Python反序列化时,我没有得到相同的对象

python - 从哪里开始编写用于将本地目录同步到 Google Drive 的 Python 脚本?

javascript - 为什么 JavaScript 中的日期操作很奇怪

java - Android SQLite 日期查询