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

Viewed 76966

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

7 Answers

Well, it's been a dozen years since this question was asked. And now (in C++20) it finally has a better answer.

Yes, there are several standard date/time classes in C++20 (not just one). Each serves different purposes in a strongly typed system. For example std::chrono::zoned_time represents a pairing of a std::chrono::time_zone and a std::chrono::time_point<system_clock, SomeDuration>, and represents the local time in some geographic area. Here is how you might create and print the local time in your current time zone to the finest sub-second precision your OS allows.

cout << zoned_time{current_zone(), system_clock::now()} << '\n';

If you need the local time somewhere else, that is just as easily obtained:

cout << zoned_time{"Africa/Casablanca", system_clock::now()} << '\n';

Unlike in previous C++ standards, time_points based on system_clock are now guaranteed to represent UTC, neglecting leap seconds (aka Unix Time). So to get the current time in UTC it is simply:

cout << system_clock::now() << '\n';

Though if you really wanted to use a zoned_time instead (for example the code may be generic), this also works:

cout << zoned_time{"UTC", system_clock::now()} << '\n';

See https://en.cppreference.com/w/cpp/chrono for many more standard date/time classes. All of them are thread-safe. And you are no longer limited to seconds precision.

Related