Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

 time_t tm(); ostringstream sout; sout << tm << ends; 

In this case I get the current date/time written out as a number without any formatting. I can use c- runtime function strftime to format tm first, but that seems like it should not be necessary if the stl has a time class that can be instantiated from time_t value

like image 663
Farid Z Avatar asked Oct 30 '09 16:10

Farid Z


People also ask

Is DateTime a class?

The DateTime class provides various functions to deal with the DateTime objects like we can convert DateTime object to string and string to DateTime objects, we can also get the weekday for the particular day of the week of the particular month, we can also set the time zone for a particular DateTime object, etc.


2 Answers

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.

like image 122
jdehaan Avatar answered Oct 05 '22 18:10

jdehaan


EDIT

The standard "datetime" class is std::chrono::time_point since C++11. The code in the question should be roughly equivalent to

const auto now = std::chrono::system_clock::now(); const auto t_c = std::chrono::system_clock::to_time_t(now); std::cout << std::put_time(std::localtime(&t_c), "%F %T.\n"); 

OLD ANSWER

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.

like image 27
mkluwe Avatar answered Oct 05 '22 20:10

mkluwe