計算兩個日期間的天數差,標準方法是將各日期轉換為「從基準日(如公元1年1月1日)起的總天數」,相減即得差值。
long dateToDays(int y, int m, int d) {
static const int monthDays[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
long total = 0;
// 累積完整年份天數
for (int i = 1; i < y; i++)
total += isLeapYear(i) ? 366 : 365;
// 累積完整月份天數
if (isLeapYear(y)) monthDays[2] = 29;
for (int i = 1; i < m; i++)
total += monthDays[i];
// 加上當月天數
total += d;
return total;
}
#include <stdio.h>
#include <time.h>
int isLeapYear(int y) {
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
long dateToDays(int y, int m, int d) {
int monthDays[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
long days = 0;
for (int i = 1; i < y; i++)
days += isLeapYear(i) ? 366 : 365;
if (isLeapYear(y)) monthDays[2] = 29;
for (int i = 1; i < m; i++)
days += monthDays[i];
return days + d;
}
int main() {
int by, bm, bd;
printf("輸入出生日期 (年 月 日): ");
scanf("%d %d %d", &by, &bm, &bd);
// 獲取系統當前日期
time_t now = time(NULL);
struct tm *t = localtime(&now);
int cy = t->tm_year + 1900;
int cm = t->tm_mon + 1;
int cd = t->tm_mday;
long birthDays = dateToDays(by, bm, bd);
long currentDays = dateToDays(cy, cm, cd);
long livedDays = currentDays - birthDays;
printf("出生日期: %04d-%02d-%02d\n", by, bm, bd);
printf("今日日期: %04d-%02d-%02d\n", cy, cm, cd);
printf("生存天數: %ld 天\n", livedDays);
return 0;
}
time.h 獲取系統日期,避免手動輸入今日日期long) 防止天數溢出(約支援200萬年)同樣邏輯可用於:計算兩日期間隔、倒數日提醒、年齡精確計算、金融利息天數計算等場景。