C++11 包括用于日期/时间表示的便捷数据类型和函数,以及它们到字符串的转换。
有了它,你可以做这样的事情(我认为非常不言自明):
#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") << '\n';
}
特别是有std::time_t 和std::tm 的数据类型,以及用于漂亮打印的非常好的IO 操纵器std::put_time。它使用的格式字符串在cppreference 有详细记录。
这也应该与语言环境很好地协同工作,例如对于日本时间/日期格式:
std::cout.imbue(std::locale("ja_JP.utf8"));
std::cout << "ja_JP: " << std::put_time(&tm, "%c %Z") << '\n';
C++11 标准库中包含的chrono 库还允许您方便地进行简单的时间/日期运算:
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));
不幸的是,目前并非所有编译器都提供所有这些功能。 特别是,std::put_time 函数似乎在 GCC 4.7.1 中不可用。为了让我最初提供的代码能够正常工作,我不得不使用稍微不那么优雅的 std::strftime 函数:
#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;
}