time_t tr_timediff(const tm * ptm1, const tm * ptm2) { uint16_t year; uint32_t days = 0; uint8_t n; uint64_t time = 0; tm * pendtm = NULL; uint8_t nptm1monthday = 0; assert(ptm1 != NULL); if (NULL == ptm2) { //計算本地時間 tr_time(pendtm);assert(pendtm != NULL); } else { pendtm = ptm2; } if if (pendtm->tm_year != ptm1->tm_year) { //不是同一年 year = pendtm->tm_year - 1; while (year > ptm1->tm_year) { //計算全年天數 if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { days += 366; } else { days += 365; } year -= 1; } for (n = 12; n >= ptm1->tm_month; --n) { //計算開始時間月數 switch (n) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: { if (n == ptm1->tm_month) { nptm1monthday = 31; } else { days += 31; } } break; case 4: case 6: case 9: case 11: { if (n == ptm1->tm_month) { nptm1monthday = 30; } else { days += 30; } } break; case 2: { if (n == ptm1->tm_month) { if (((ptm1->tm_year) % 4 == 0 && (ptm1->tm_year) % 100 != 0) || (ptm1->tm_year) % 400 == 0) { nptm1monthday = 29; } else { nptm1monthday = 28; } } else { if (((ptm1->tm_year) % 4 == 0 && (ptm1->tm_year) % 100 != 0) || (ptm1->tm_year) % 400 == 0) { days += 29; } else { days += 28; } } } } } for (n = 1; n < pendtm->tm_month; ++n) { //計算結束時間月數 switch (n) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: { days += 31; } break; case 4: case 6: case 9: case 11: { days += 30; } break; case 2: { if (((pendtm->tm_year) % 4 == 0 && (pendtm->tm_year) % 100 != 0) || (pendtm->tm_year) % 400 == 0) { days += 29; } else { days += 28; } } } } days += pendtm->tm_day - 1;//累加結束時間天數 days += nptm1monthday - ptm1->tm_day;//累加開始時間天數 time = (days * 24 * 60 * 60) + (pendtm->tm_hour * 3600 + pendtm->tm_minute * 60 + pendtm->tm_second) + ((24 - ptm1->tm_hour - 1) * 3600 + ((60 - ptm1->tm_minute - 1) * 60) + 60 - ptm1->tm_second); } else { //開始時間和結束時間是同一年 for (n = ptm1->tm_month; n < pendtm->tm_month; ++n) { //計算開始和結束月份 switch (n) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: { if (n == ptm1->tm_month) { nptm1monthday = 31; } else { days += 31; } } break; case 4: case 6: case 9: case 11: { if (n == ptm1->tm_month) { nptm1monthday = 30; } else { days += 30; } } break; case 2: { if (n == ptm1->tm_month) { if (((ptm1->tm_year) % 4 == 0 && (ptm1->tm_year) % 100 != 0) || (ptm1->tm_year) % 400 == 0) { nptm1monthday = 29; } else { nptm1monthday = 28; } } else { if (((ptm1->tm_year) % 4 == 0 && (ptm1->tm_year) % 100 != 0) || (ptm1->tm_year) % 400 == 0) { days += 29; } else { days += 28; } } } } } if (ptm1->tm_month != pendtm->tm_month) { //若是開始時間和結束時間不是同一月 days += pendtm->tm_day;//累加結束時間天數 days += nptm1monthday - ptm1->tm_day;//累加開始時間天數 } else { //同年同月中 days += pendtm->tm_day - ptm1->tm_day; } time = (days * 24 * 60 * 60) + ((pendtm->tm_hour - ptm1->tm_hour) * 3600 + (pendtm->tm_minute - ptm1->tm_minute) * 60 + pendtm->tm_second - ptm1->tm_second); } return time; }