在单片机中需要计算任意连个时间点的相隔时间差,一般情况下是在需要使用RTC时钟进行定时计数时使用,程序代码如下:
1 #include <stdio.h> 2 3 typedef struct Time{ 4 int Y,M,D,h,m,s; 5 }Time; 6 7 Time time1 = {20,7,28,5,30,10}; 8 Time time2 = {20,7,29,6,10,10}; 9 10 /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 11 *函数名称:Day_Diff 12 *函数功能:计算任意日期的相隔天数 13 *输入参数:time1 结构体指针 , time2结构体指针 14 *返回参数:天数 15 * <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ 16 int Day_Diff(Time *time1 , Time *time2) 17 { 18 int year2 , month2 , day2; 19 int year1 , month1 , day1; 20 month1 = (time1->M + 9)%12; 21 year1 = time1->Y - month1/10; 22 day1 = 365 * year1 + year1 / 4 - year1 / 100 + year1 / 400 + (month1 *306 + 5) / 10 + (time1->D - 1); 23 24 month2 = (time2->M + 9) % 12; 25 year2 = time2->Y - month2 / 10; 26 day2 = 365 * year2 + year2 / 4 - year2 / 100 + year2 / 400 + (month2 *306 + 5) / 10 + (time2->D - 1); 27 return (day2 - day1); 28 } 29 30 /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 31 *函数名称:TimeSub 32 *函数功能:计算任意两个时间点相隔分钟数 33 *输入参数:Day 天数 , time1 结构体指针 , time2结构体指针 34 *返回参数: 35 * <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ 36 int TimeSub(int Day , Time *time1,Time *time2) 37 { 38 long t1,t2,t; 39 t1 = (time1->h * 3600) + (time1->m * 60) + (time1 -> s); 40 t2 = (Day * 24 *3600) + (time2->h * 3600) + (time2->m *60) + (time2 -> s); 41 42 t = (t2 - t1) /60; 43 return t; 44 } 45 46 47 int main() 48 { 49 int num = 0; 50 int day = 0; 51 day = Day_Diff(&time1 , &time2); 52 printf("day = %d\r\n",day); 53 num = TimeSub(day,&time1 , &time2); 54 printf("%d\r\n" , num); 55 return 0; 56 }
Day_Diff函数用来计算两个日期之间的相隔天数,主要是为了解决如果当前时间是23:30,而计时后的时间到了00:30,而导致的无法直接计算分钟数的问题;
TimeSub函数用来计算任意时间点的相隔分钟数,主要思想是将所有时间转化为秒并相加,得到总的秒钟数后除以60转为分钟,即得到了所需要的分钟数;