【问题标题】:How to format a datetime to string using boost?如何使用boost将日期时间格式化为字符串?
【发布时间】:2011-06-28 10:32:47
【问题描述】:

我想使用 boost 将日期/时间格式化为字符串。

从当前日期/时间开始:

ptime now = second_clock::universal_time();

并以包含此格式的日期/时间的 wstring 结尾:

%Y%m%d_%H%M%S

你能告诉我实现这一目标的代码吗?谢谢。

【问题讨论】:

    标签: c++ formatting datetime


    【解决方案1】:

    不管它有什么价值,这里是我为此编写的函数:

    #include "boost/date_time/posix_time/posix_time.hpp"
    #include <iostream>
    #include <sstream>
    
    std::wstring FormatTime(boost::posix_time::ptime now)
    {
      using namespace boost::posix_time;
      static std::locale loc(std::wcout.getloc(),
                             new wtime_facet(L"%Y%m%d_%H%M%S"));
    
      std::basic_stringstream<wchar_t> wss;
      wss.imbue(loc);
      wss << now;
      return wss.str();
    }
    
    int main() {
      using namespace boost::posix_time;
      ptime now = second_clock::universal_time();
    
      std::wstring ws(FormatTime(now));
      std::wcout << ws << std::endl;
      sleep(2);
      now = second_clock::universal_time();
      ws = FormatTime(now);
      std::wcout << ws << std::endl;
    
    }
    

    这个程序的输出是:

    20111130_142732
    20111130_142734
    

    我发现这些链接很有用:

    【讨论】:

    • 我现在正在测试这个 - 可能是 wstringstream 需要一个 wtime_facet,而这正是我默默失败的地方。
    • 这可行,但请注意,如果您要对多个日期使用相同的格式,请不要每次都创建构面,而是创建一次然后多次使用。灌输本身并不昂贵。
    • 请注意,您可以通过存储语言环境对象来做到这一点。
    • 谢谢@CashCow。我进行了您建议的更改。
    • 对于使用 C++98 和 C++0x,我发现使用 std::stringstream 更好,因为 std::basic_stringstream 的模板不同。
    【解决方案2】:
    // create your date
    boost::gregorian::date d(2009, 1, 7); 
    
    // create your formatting
    boost::gregorian::date_facet *df = new boost::gregorian::date_facet("%Y%m%d_%H%M%S"); 
    
    // set your formatting
    ostringstream is;
    is.imbue(std::locale(is.getloc(), df));
    is << d << endl;
    
    // get string
    cout << "output :" << is.str() << endl;
    

    【讨论】:

    • 各位,认真的。在 C# 中,我可以编写 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") ,仅此而已!这些天 C++ 到底出了什么问题...
    • 你听起来像我高中时的侄子 :) 我确信你提到的函数与我上面编写的代码非常相似。如果你想要更好的用户界面,那么你必须在 boost 之上构建一个抽象层。升压设计灵活。看看 Poco C++ 库。他们有非常好的 Java 风格的界面,这使得它很容易编码。所以问题不在于 C++ :)
    • 有没有办法把它变成一个字符串变量(即std::string)而不是直接输出到控制台?
    • @romanz,然后在使用用户定义的格式而不是 yyyy-MM-dd HH:mm:ss 时尝试使用您的方法,以及特定的时区、语言/区域设置、编码、一周的第一天和月份/天的缩短将被应用。而且你会得到DateTime 支持的地狱格式,它们并不涵盖所有情况。
    猜你喜欢
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 2020-08-07
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    相关资源
    最近更新 更多