Alternatives to

后端 未结 2 1604
死守一世寂寞
死守一世寂寞 2021-02-06 09:49

I\'m looking for a C++11 version of the library. Were any like this included with C++11?

EDIT: Anything with more functionality would be perfe

2条回答
  •  臣服心动
    2021-02-06 10:18

    Many of the functions in , notably the ctime function itself, have to do with formatting dates and times as strings.

    C++11 provides a new io-manipulator std::put_time, which indeed replaces C-style functions, and is fully compatible with the locale-related features of C++.

    Specifically, given a time-point in C-style tm format:

    std::time_t t = std::time(NULL);
    std::tm tm = *std::localtime(&t);
    

    std::put_time enables printing this according to any chosen locale, if locale-specific formatting parameters, such as %c (locale-specific date/time), %Ec (locale specific, extended date/time, such as imperial years for Japan), or %Z (time-zone) are used:

    std::cout.imbue(std::locale("ja_JP.utf8"));
    std::cout << "ja_JP: " << std::put_time(&tm, "%c %Z") << '\n';
    std::cout << "ja_JP: " << std::put_time(&tm, "%Ec %Z") << '\n';
    

    These calls print something like:

    2012年11月15日 11時49分04秒 JST     // first call
    平成24年11月15日 10時49分05秒 JST   // second call
    

    The time-point retrieval functions from , mentioned in the other answer, can also be converted to a tm struct, using the to_time_t method, and then used together with put_time. This makes the code independent of any C-style function calls, at least on the surface:

    using namespace std;
    auto now = chrono::system_clock::now();
    
    time_t now_c = chrono::system_clock::to_time_t(now);
    cout << "Locale-specific time now: "
         << put_time(localtime(&now_c), "%c %Z") << '\n';
    

    Combined with duration types, this gives great flexibility in calculating and printing dates and times:

    time_t now_c = chrono::system_clock::to_time_t(now - chrono::hours(48));
    cout << "Locale-specific time on the day before yesterday: "
         << put_time(localtime(&now_c), "%c %Z") << '\n';
    

    These are the headers you need for all the function calls above:

    #include 
    #include 
    #include 
    #include 
    

    Availability note I am unsure about MSVC and Clang, but GCC, unfortunately, does not provide the std::put_time function just yet: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=54354.

提交回复
热议问题