</pre><pre name="code" class="cpp"><pre name="code" class="cpp">#include <time.h>
#include <string.h>
/*
*用来保存秒数
*/
static time_t calendar_second;
/*
*用来校准日历
*/
void cali_calendar(struct tm *p_cal)
{
calendar_second = mktime(p_cal);
}
/*
*得到日历
*/
void get_calendar(struct tm *p_cal)
{
memcpy(p_cal, localtime(&calendar_second), sizeof(struct tm));
}
/*
*更新计时用的秒数,参数表示要增加的秒数
*/
void update_calendar(int second)
{
calendar_second += second;
}
time.h中的定义
struct tm {<p> int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
};</p>
上面的函数可以用作RTC日历。
如果获得一个准确的时间就调用void cali_calendar(struct tm *p_cal)把时间转化为从1900年所经历的秒数。注意夏令时。
struct tm s_cal1, s_cal2;
s_cal1.tm_year = 2014 -1900;
s_cal1.tm_mon = 10 -1;
s_cal1.tm_mday = 1;
s_cal1.tm_hour = 9;
s_cal1.tm_min = 30;
s_cal1.tm_sec = 0;
s_cal1.tm_isdst = 0;//这个要设为0,否则可能会因为夏令时而差一个小时
cali_calendar(&s_cal1);
然后每个一秒调用一次void update_calendar(1)。
然后需要得到年月日时分秒的时候就调用void get_calendar(struct tm *p_cal)。
如果想得到两天之间相隔的天数可以用
struct tm time1;
struct tm time2;
//time1设为某一天,注意夏令时
//time2设为另一天
int day;
day = (mktime(&time1) - mktime(&time2))/(60*60*24);