时间函数的定义包含在头文件<time.h>中,所以首先得声明头文件。而时间相关的函数简单介绍如下:
linux下存储时间常见的有两种存储方式,一个是从1970年到现在经过了多少秒,一个是用一个结构来分别存储年月日时分秒的。
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*/ 1+p->tm_mon;
int tm_year; /*年, 从1900至今已经多少年*/ 1900+ p->tm_year;
int tm_wday; /*星期,一周中的第几天, 从星期日算起,0-6*/
int tm_yday; /*从今年1月1日到目前的天数,范围0-365*/
int tm_isdst; /*日光节约时间的旗标*/
};
需要特别注意的是,年份是从1900年起至今多少年,而不是直接存储如2011年,月份从0开始的,0表示一月,星期也是从0开始的, 0表示星期日,1表示星期一。
下面介绍一下我们常用的时间函数:
#include <time.h>
char *asctime(const struct tm* timeptr);
将结构中的信息转换为真实世界的时间,以字符串的形式显示
char *ctime(const time_t *timep);
将timep转换为真是世界的时间,以字符串显示,它和asctime不同就在于传入的参数形式不一样
double difftime(time_t time1, time_t time2);
返回两个时间相差的秒数
int gettimeofday(struct timeval *tv, struct timezone *tz);
返回当前距离1970年的秒数和微妙数,后面的tz是时区,一般不用
struct tm* gmtime(const time_t *timep);
将time_t表示的时间转换为没有经过时区转换的UTC时间,是一个struct tm结构指针
stuct tm* localtime(const time_t *timep);
和gmtime类似,但是它是经过时区转换的时间。
time_t mktime(struct tm* timeptr);
将struct tm 结构的时间转换为从1970年至今的秒数
time_t time(time_t *t);
取得从1970年1月1日至今的秒数。
(要取代码的旁友,请仔细看最后的文字!!!或直接取第二段代码)
代码如下:
#include <iostream>
#include <time.h>
#include <stdio.h>
using namespace std;
time_t convert(int year, int mon, int day, int hour, int min, int sec, int week)
{
tm info;
info.tm_year = year-1900;
info.tm_mon = mon;
info.tm_mday = day;
info.tm_hour = hour;
info.tm_min = min;
info.tm_sec = sec;
info.tm_wday = week;
return mktime(&info); // mktime()函数可以将tm结构体转化成秒值也就是time_t类型
}
int main()
{
int s_year, s_mon, s_day;
cout << "请输入开始的日期(xxxx xx xx):" ;
cin >> s_year >> s_mon >> s_day ;
time_t start = convert(s_year, s_mon, s_day, 0, 0, 0, 0);
cout << "请输入结束的日期(xxxx xx xx):" ;
int e_year , e_mon, e_day;
cin >> e_year >> e_mon >> e_day;
time_t end = convert(e_year, e_mon, e_day, 0, 0, 0, 0);
int diff = (int) (end - start);
int days = diff/(60*60*24);
cout << "中间相差了" << days << "天。" << endl;
system("pause");
return 0;
}感觉上是没错,但是输入如下:

那么错出在哪里呢,我在网上找来了另一段代码,如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<time.h>
int get_days(const char* from, const char* to);
time_t convert(int year,int month,int day);
int main()
{
const char* from="2019-6-20";
const char* to="2019-8-01";
int days=get_days(from,to);
printf("From:%s\nTo:%s\n",from,to);
printf("%d\n",days);
system("pause");
return 0;
}
time_t convert(int year,int month,int day)
{
tm info={0};
info.tm_year=year-1900;
info.tm_mon=month-1;
info.tm_mday=day;
return mktime(&info);
}
可见相同的输入,但是输出结果不同,通过自己的计算,输出应该是第二结果42天才对。
对比两段代码可知,在mon这一项上,后一段代码-1而我自己写的没有减,由此造成了结果上的差异。在tm这个结构体中,月份的存储是从0开始的,所以在反向转换的时候要在输入的mon基础上先减个一。