直接顯示當前時間:
1 #include <iostream> 2 #include <ctime> 3 using namespace std; 4 int main() 5 { 6 time_t now = time(0); 7 char *dt = ctime(&now); 8 cout << dt; 9 }
顯示當前的年月日,時分秒:
1 #include <iostream> 2 #include <ctime> 3 using namespace std; 4 int main() 5 { 6 time_t now = time(0); 7 tm *ltm = localtime(&now); 8 cout << "年" << 1900 + ltm->tm_year << endl; 9 cout << "月" << 1 + ltm->tm_mon << endl; 10 cout << "日" << ltm->tm_mday << endl; 11 cout << "時" << ltm->tm_hour << endl; 12 cout << "分" << ltm->tm_min << endl; 13 cout << "秒" << ltm->tm_sec << endl; 14 }