C ++标准库不提供正确的日期类型。C ++从C继承了日期和时间操作的结构体和函数。要访问与日期和时间相关的函数和结构,需要在C ++程序中包含 <ctime>
头文件。
有四个与时间相关的类型:clock_t
,time_t
,size_t
,和tm
。类型clock_t,size_t和time_t能够表示系统时间和日期作为某种整数。
结构类型 tm
以具有以下元素的C结构的形式保存日期和时间:
struct tm {
int tm_sec; // seconds of minutes from 0 to 61
int tm_min; // minutes of hour from 0 to 59
int tm_hour; // hours of day from 0 to 24
int tm_mday; // day of month from 1 to 31
int tm_mon; // month of year from 0 to 11
int tm_year; // year since 1900
int tm_wday; // days since sunday
int tm_yday; // days since January 1st
int tm_isdst; // hours of daylight savings time
}
使用 struct tm
来格式化时间,以下为演示Demo:
#include <iostream>
#include <ctime>
using namespace std;
int main( ) {
// current date/time based on current system
time_t now = time(0);
cout << "Number of sec since January 1,1970:" << now << endl;
tm *ltm = localtime(&now);
// print various components of tm structure.
cout << "Year: " << 1900 + ltm->tm_year<<endl;
cout << "Month: "<< 1 + ltm->tm_mon<< endl;
cout << "Day: "<< ltm->tm_mday << endl;
cout << "Time: "<< 1 + ltm->tm_hour << ":";
cout << 1 + ltm->tm_min << ":";
cout << 1 + ltm->tm_sec << endl;
}
References
C++ Date and Time.