【问题标题】:How to format a chrono::time_point as a string如何将 chrono::time_point 格式化为字符串
【发布时间】:2019-05-26 15:48:29
【问题描述】:

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

【问题讨论】:

  • 使用stringstream 随意格式化
  • this answer。使用"%FT%T" 作为格式字符串而不是"%c"。除非需要比较日期和时间间隔,否则不需要使用std::chrono
  • UTC、本地时区,还是某个特定的非本地时区?
  • @HowardHinnant UTC

标签: c++ time chrono


【解决方案1】:

最简单的方法是使用Howard Hinnant's free, open-source, header-only 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 库保持一致。

【讨论】:

    【解决方案2】:
    #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;
    
    }
    

    【讨论】:

    • 你知道这不是 UTC 吗?
    猜你喜欢
    • 2016-04-23
    • 2020-05-30
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2014-01-28
    • 2017-07-14
    • 2015-03-26
    相关资源
    最近更新 更多