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;
}
我建议得到一些日期时间库。请参阅[boost.datetime](http://www.boost.org/doc/libs/1_51_0/doc/html/date_time.html)。 – juanchopanza
使用boost库,或为您需要的操作系统“日期”函数编写简单的类封装器。如果要保存到数据库,使用“DateTime”,否则使用字符串(可能是JSON字符串,也许是XML字符串,或者可能只是一个平面文件)可以读取和写入日期。 – paulsm4