1. 包含头文件
# include <time.h> c++
# include <ctime> c
2. 相关数据类型、数据结构
(1) time_t
(2) struct tm
结构体tm 包括9中int型变量
Member | Meaning | Range |
---|---|---|
tm_sec | seconds after the minute | 0-61* |
tm_min | minutes after the hour | 0-59 |
tm_hour | hours since midnight | 0-23 |
tm_mday | day of the month | 1-31 |
tm_mon | months since January | 0-11 |
tm_year | years since 1900 | |
tm_wday | days since Sunday | 0-6 |
tm_yday | days since January 1 | 0-365 |
tm_isdst | Daylight Saving Time flag |
3. 转换函数
localtime ://Convert time_t to tm as local time
asctime // Convert tm structure to stringmktime //Convert tm structure to time_t
strptime //conver str to tm structure 按照特定时间格式将字符串转换为时间类型。
4. 用法举例
time_t my_time;
time (&my_time) ; 或者my_time= time(NULL) // seconds since January 1,1970 to now
struct tm * timeinfo;
timeinfo =localtime(&my_time);
time_t new_time;
new_time =mktime();
char fmt[] = "%Y-%m-%d-%H:%M:%S";
char buf[] = "2000-01-01-00:00:00"; strptime(buf, fmt, timeinfo) ;