C++で日付や時刻を扱うには
time()関数で現在の日付と時刻がtime_t型で得られる。time_t型はlong int型で定義されている。これから月や分、秒などを得るにはtm構造体を用いる。tm構造体はVisualC++では次のように定義されている。
struct tm { int tm_sec; /* seconds after the minute - [0,59] */ int tm_min; /* minutes after the hour - [0,59] */ int tm_hour; /* hours since midnight - [0,23] */ int tm_mday; /* day of the month - [1,31] */ int tm_mon; /* months since January - [0,11] */ int tm_year; /* years since 1900 */ int tm_wday; /* days since Sunday - [0,6] */ int tm_yday; /* days since January 1 - [0,365] */ int tm_isdst; /* daylight savings time flag */ };
日付と時刻を文字列に変換するにはasctime()関数を使う。これらを実際に使う場合はつぎのような感じ。
#include <iostream> #include <ctime> using namespace std; int main() { struct tm *now; time_t longtime; longtime = time(NULL); now = localtime(&longtime); cout << asctime(now); return 0; } 実行結果: Sat Apr 26 03:20:05 2008
VisualC++でコンパイルすると、localtime()関数とasctime()関数は安全でないとwarningが出る。より安全になったlocaltime_s()関数とasctime_s()関数を使う。
#include <iostream> #include <ctime> using namespace std; int main() { struct tm now; time_t longtime; char timestr[32]; longtime = time(NULL); localtime_s(&now, &longtime); asctime_s(timestr, sizeof(timestr), &now); cout << timestr; return 0; }