C++11 includes convenience data types and functions for date/time representations, as well as their conversion to strings.
With that, you can do things like this (pretty self-explanatory, I think):
#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
std::time_t t = std::time(NULL);
std::tm tm = *std::localtime(&t);
std::cout << "Time right now is " << std::put_time(&tm, "%c %Z") << '
';
}
In particular, there are data types std::time_t
and std::tm
, and a very nice IO manipulator std::put_time
for pretty printing. The format strings used by it are well-documented at cppreference.
This is also supposed to work together well with locales, e.g. for a Japanese time/date format:
std::cout.imbue(std::locale("ja_JP.utf8"));
std::cout << "ja_JP: " << std::put_time(&tm, "%c %Z") << '
';
The chrono
library included in the C++11 standard library also allows you to do simple time/date arithmetic conveniently:
std::chrono::time_point<std::chrono::system_clock> now;
now = std::chrono::system_clock::now();
/* The day before today: */
std::time_t now_c = std::chrono::system_clock::to_time_t(
now - std::chrono::hours(24));
Unfortunately, not all of this is available in all compilers yet. In particular, the std::put_time
function does not seem to be available in GCC 4.7.1 yet. To get the code I gave initially to work, I had to use the slightly less elegant std::strftime
function:
#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
std::time_t t = std::time(NULL);
std::tm tm = *std::localtime(&t);
constexpr int bufsize = 100;
char buf[bufsize];
if (std::strftime(buf,bufsize,"%c %Z",&tm) != 0)
std::cout << "Time right now is " << buf << std::endl;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…