- /**********************************************************************************************************************************
- 【数据类型】(1)time_t:可理解为int类型
- (2)struct tm:结构体类型,里面的数据成员均为int类型,tm_year、tm_mon、tm_day、tm_hour、tm_min、tm_sec
- 【主要函数】(1)time(): 获取当前的系统时间,返回的结果是一个time_t类型,其值表示从1970年1月1日00:00:00到当前时刻的秒数。
- (2)localtime(): 把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间,即将time_t转化为struct tm(本地时间、日历时间)
- (3)mktime():将时间(struct tm)转换为自1970年1月1日以来失去时间的秒数(time_t),返回经过的秒数,发生错误时返回-1。
- (4)strptime():按照特定时间格式将字符串转换为struct tm时间类型(日历时间、本地时间)。
- (5)strftime():根据区域设置格式化本地时间/日期,或者说格式化一个时间字符串;struct tm时间类型转换成字符串形式。
- *************************************************************************************************************************************/
- #include <stdio.h>
- #include <time.h>
- int main()
- {
- time_t timep;
- struct tm *p;
- time(&timep);
- printf("time():%d\n", (int)timep);
- p = localtime(&timep);
- printf("%4d-%2d-%2d %2d-%2d-%2d\n", p->tm_year + 1990, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);
- struct tm tm_time;
- strptime("2013-11-15 15:45:23", "%Y-%m-%d %H:%M:%S", &tm_time);
- printf("%ld\n", mktime(&tm_time));
- printf("%4d-%2d-%2d %2d-%2d-%2d\n", tm_time.tm_year + 1990, tm_time.tm_mon + 1, tm_time.tm_mday, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec);
- tm_time.tm_sec += 2;//实现时间的加减
- printf("%4d-%2d-%2d %2d-%2d-%2d\n", tm_time.tm_year + 1990, tm_time.tm_mon + 1, tm_time.tm_mday, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec);
- }
linux下存储时间常见的有两种存储方式: (1)用一个time_t(类似int)变量来表示,记录从1970年到现在经过了多少秒;(2)用一个struct tm结构体变量表示,分别存储年月日时分秒。
time_t:用来存储从1970年到现在经过了多少秒 ,要想更精确一点,可以用结构struct timeval,它精确到微妙。
- struct timeval
- {
- long tv_sec; /*秒*/
- long tv_usec; /*微秒*/
- };
- struct tm
- {
- int tm_sec; /*秒,正常范围0-59, 但允许至61*/
- int tm_min; /*分钟,0-59*/
- int tm_hour; /*小时, 0-23*/
- int tm_mday; /*日,即一个月中的第几天,1-31*/
- int tm_mon; /*月, 从一月算起,0-11*/
- int tm_year; /*年, 从1900至今已经多少年*/
- int tm_wday; /*星期,一周中的第几天, 从星期日算起,0-6*/
- int tm_yday; /*从今年1月1日到目前的天数,范围0-365*/
- int tm_isdst; /*日光节约时间的旗标*/
- };
(2)函数详解
1、得到系统时间
- time_t time(time_t *timer) ;
2、time_t类型和struct tm类型之间的转换
- struct tm *localtime(const time_t *timer);
- time_t mktime(struct tm * timeptr);
mktime():将struct tm类型时间(日历时间、本地时间)转换为自1970年1月1日以来失去时间的秒数(time_t),返回经过的秒数,发生错误时返回-1。
3、转换成字符串形式的时间格式
- char *ctime(const time_t *timep);
- char *asctime(const struct tm* timeptr);
4、计算时间差
- double difftime(time_t starttime, time_t endtime);
5、时间格式化输出
- char *strptime(const char *buf,const char *format, struct tm *tm);
- size_t strftime(char *strDest,size_t maxsize,const char *format,const struct tm *timeptr);
strftime():根据format指向字符串中格式命令把timeptr中保存的时间信息放在strDest指向的字符串中,最多向strDest中存放maxsize个字符。该函数返回向strDest指向的字符串中放置的字符数。