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