如何将 chrono::time_point 格式化为字符串

问题描述 投票:0回答:2

我需要在 C++ 中获取当前日期和时间。我可以使用

chrono
来获取
system time
但我还需要将其保存在 json 文件中作为字符串。此外,我尝试过的计时时间给出了以下格式:

auto time = std::chrono::system_clock::now();

输出:

Thu Oct 11 19:10:24 2012

但是我需要以下格式的日期时间格式:

2016-12-07T00:52:07

我还需要字符串形式的日期时间,以便我可以将其保存在 Json 文件中。任何人都可以建议一个好方法来实现这一目标。谢谢。

c++ time c++-chrono
2个回答
3
投票

最简单的方法是使用 Howard Hinnant 的免费、开源、仅标头的 date.h:

#include "date/date.h"
#include <iostream>
#include <string>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto time = system_clock::now();
    std::string s = format("%FT%T", floor<seconds>(time));
    std::cout << s << '\n';
}

该库是新的 C++20、chrono 扩展的原型。尽管在 C++20 中,格式的细节可能会略有变化,以使其与预期的 C++20

fmt
库保持一致。

C++20版本

#include <chrono>
#include <iostream>
#include <format>
#include <string>

int
main()
{
    auto time = std::chrono::system_clock::now();
    std::string s = std::format("{:%FT%T}",
                       std::chrono::floor<std::chrono::seconds>(time));
    std::cout << s << '\n';
}

演示。


0
投票
#include <iostream>
#include <chrono>
#include <ctime>

std::string getTimeStr(){
    std::time_t now =     std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());

    std::string s(30, '\0');
    std::strftime(&s[0], s.size(), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
    return s;
}
int main(){

    std::cout<<getTimeStr()<<std::endl;
    return 0;

}
© www.soinside.com 2019 - 2024. All rights reserved.