c time.h

</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);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值