Is there a standard date/time class in C++?

前端 未结 6 1214
悲哀的现实
悲哀的现实 2020-12-01 14:05

Does C++ stl have a standard time class? Or do I have to convert to c-string before writing to a stream. Example, I want to output the current date/time to a string stream:<

相关标签:
6条回答
  • 2020-12-01 14:29

    C++ now has the chrono libraries for date and time. This is documented on http://en.cppreference.com/w/cpp/chrono and http://www.cplusplus.com/reference/chrono/

    0 讨论(0)
  • 2020-12-01 14:30

    Not part of STL but well known library is boost.

    I would go the way of using boost::date. Here are some examples: http://www.boost.org/doc/libs/1_55_0/doc/html/date_time/date_time_io.html#date_time.io_tutorial.

    If you did not try out boost yet I encourage you to do so as it saves you from a lot of nasty issues, as it masks most OS dependent things like threading for example. Many things in boost are header only (template libraries). However datetime requires a lib or dll.

    0 讨论(0)
  • 2020-12-01 14:38

    There are get_time and put_time in <iomanip> header (i guess these came with C++11) which effectively does string formatting or parsing jobs.

    0 讨论(0)
  • 2020-12-01 14:38

    There is also a ctime(&time_t) method which outputs string (char*).

    0 讨论(0)
  • 2020-12-01 14:41

    Nitpicking: The STL being the Standard Template Library deals with generic container and algorithms etc. and is unlikely to incorporate classes for date handling and calculation even in the future…

    The C++ Standard Library itself includes the STL and a previous version of the C standard library. The latter offers some date and time related functions via #include <ctime> which has already been mentioned above.

    If wrapping (or simply using) these functions is sufficient (and quicker) than pulling in boost, go with these. There is nothing wrong with them.

    0 讨论(0)
  • 2020-12-01 14:42

    OK. Here is closest I have found about directly writing time to a stream:

    time_t t(time(NULL));   // current time
    tm tm(*localtime(&t));  
    
    std::locale loc("");    // current user locale
    ostringstream sout;
    const std::time_put<TCHAR> &tput =
        std::use_facet<std::time_put<TCHAR> >(loc);
    tput.put(sout.rdbuf(), sout, _T('\0'), &tm, _T('x'));
    sout << ends;
    
    CString sTest(sout.str().c_str());
    

    A very helpful guide is the Apache C++ Standard Library Reference Guide http://stdcxx.apache.org/doc/stdlibref/time-put.html#sec13

    0 讨论(0)
提交回复
热议问题