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

How to format a chrono::time_point as a string

本文关键字:point 格式化 字符串 time Chrono      更新时间:2023-10-16

我需要在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文件中。任何人都可以提出一种实现这一目标的好方法。谢谢。

最简单的方法是使用霍华德·辛南特(Howard Hinnant(的免费,开源,仅标题日期。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库。

#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, '');
    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;
}