- How to turn a date into a single number of days from a fixed starting point
- Why this conversion makes date arithmetic simple — subtraction, comparison, everything
- How to handle leap years with the 4/100/400 rule
- Why we take the absolute value at the end
- How two structs, one helper function, and a couple of lines of arithmetic do the whole job
Turning a date into a number
The tricky part of date arithmetic isn't the subtraction — it's the fact that months have different lengths, and years change February from 28 days to 29. You can't just do "days difference = day1 - day2 + 30 * (month1 - month2) + 365 * (year1 - year2)" because that's wrong whenever a month has 31 days, or February has 29, or the dates straddle a leap year.
The clean way to handle this is to convert each date into a single number: how many days it is from a fixed starting point. Then the difference between two dates is just the difference between two numbers. Pick any starting point you like — 1 January 0000, or 1 January 1900, or whatever — as long as you use the same starting point for both dates. The difference comes out the same.
The conversion formula is straightforward if you break it into pieces. Count the whole years before the given year (each contributes 365 days, plus one extra for each leap year). Count the whole months before the given month in that year, using a small table of month lengths. Then add the day. That's the total. For 2024-12-25: 2024 years × 365, plus 490 leap days (roughly), plus the 11 months before December in 2024, plus 25. The formula's a bit long, but each part is simple.
💡 In one line: convert each date to "days since a fixed starting date", then subtract. Leap years are handled inside the conversion. Take the absolute value at the end so the answer is always positive.
The day-count formula
Here's the helper function that does the conversion. It takes a struct date and returns the number of days from a fixed starting point (1 January of year 0, treated as year 1 in the calculation).
long days_since_epoch(struct date d) {
long total = 0;
/* Count days in all years before this one */
for (int y = 1; y < d.year; y++) {
total += is_leap(y) ? 366 : 365;
}
/* Count days in all months before this one in this year */
for (int m = 1; m < d.month; m++) {
total += days_in_month(m, d.year);
}
/* Add the day number itself */
total += d.day;
return total;
}
The two loops are the key. The first walks through every year before d.year and adds 365 or 366 depending on whether it's a leap year. The second walks through every month before d.month in d.year and adds the right number of days for each. Then the day is added directly. Simple and correct, though not the fastest for very large years — a closed-form formula exists, but the loop version is much easier to read and check.
| Month | Days (normal year) | Days (leap year) |
|---|---|---|
| January | 31 | 31 |
| February | 28 | 29 |
| March | 31 | 31 |
| April | 30 | 30 |
| May | 31 | 31 |
| June | 30 | 30 |
| July | 31 | 31 |
| August | 31 | 31 |
| September | 30 | 30 |
| October | 31 | 31 |
| November | 30 | 30 |
| December | 31 | 31 |
Complete C Program
Program: difference between two dates in days
#include <stdio.h>
#include <stdlib.h>
struct date {
int day;
int month;
int year;
};
int is_leap(int y) {
if (y % 400 == 0) return 1;
if (y % 100 == 0) return 0;
return y % 4 == 0;
}
int days_in_month(int m, int y) {
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (m == 2 && is_leap(y)) return 29;
return days[m - 1];
}
long days_since_epoch(struct date d) {
long total = 0;
for (int y = 1; y < d.year; y++)
total += is_leap(y) ? 366 : 365;
for (int m = 1; m < d.month; m++)
total += days_in_month(m, d.year);
total += d.day;
return total;
}
int main(void) {
struct date a = {15, 8, 2023};
struct date b = {25, 12, 2024};
long diff = labs(days_since_epoch(b) - days_since_epoch(a));
printf("Date 1 : %02d/%02d/%d\n", a.day, a.month, a.year);
printf("Date 2 : %02d/%02d/%d\n", b.day, b.month, b.year);
printf("Difference : %ld days\n", diff);
return 0;
}
And here's a version that reads both dates from the user, so you can try any pair you like:
Variant: read both dates from the user
#include <stdio.h>
#include <stdlib.h>
struct date {
int day;
int month;
int year;
};
int is_leap(int y) {
if (y % 400 == 0) return 1;
if (y % 100 == 0) return 0;
return y % 4 == 0;
}
int days_in_month(int m, int y) {
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (m == 2 && is_leap(y)) return 29;
return days[m - 1];
}
long days_since_epoch(struct date d) {
long total = 0;
for (int y = 1; y < d.year; y++)
total += is_leap(y) ? 366 : 365;
for (int m = 1; m < d.month; m++)
total += days_in_month(m, d.year);
total += d.day;
return total;
}
int main(void) {
struct date a, b;
printf("Enter first date (dd mm yyyy): ");
scanf("%d %d %d", &a.day, &a.month, &a.year);
printf("Enter second date (dd mm yyyy): ");
scanf("%d %d %d", &b.day, &b.month, &b.year);
long diff = labs(days_since_epoch(b) - days_since_epoch(a));
printf("\n%02d/%02d/%d to %02d/%02d/%d\n",
a.day, a.month, a.year, b.day, b.month, b.year);
printf("Difference : %ld days\n", diff);
return 0;
}
The two versions use the same helper functions — the only difference is where the dates come from. Once the helpers are written, the difference is a single line: labs(days_since_epoch(b) - days_since_epoch(a)). That's the payoff of converting to day numbers: everything else becomes subtraction.
Program Output
Date 1 : 15/08/2023
Date 2 : 25/12/2024
Difference : 498 days
And for the user-input version, try two dates in the same year — say 1 January 2024 and 31 December 2024:
Enter first date (dd mm yyyy): 1 1 2024
Enter second date (dd mm yyyy): 31 12 2024
01/01/2024 to 31/12/2024
Difference : 365 days
That's 365, not 366, because 2024 is a leap year and the leap day (29 February) is included. Try 1 January 2023 to 31 December 2023 — that should be 364 days (since 2023 is not a leap year). Try the same date twice — that should be 0 days. Try swapping the two dates — the answer should stay the same, thanks to labs.
Step-by-Step Explanation
Let's walk through the key pieces.
1. The struct
Same struct date as the last two assignments. Nothing new. Two variables a and b hold the two dates we want to compare.
2. The leap-year helper
is_leap(y) returns 1 for a leap year and 0 otherwise. The rule is: divisible by 4 → leap, unless divisible by 100 → not leap, unless divisible by 400 → leap. So 2000 is a leap year (divisible by 400), 1900 is not (divisible by 100 but not 400), 2024 is (divisible by 4). The function checks these conditions in order, with the 400 rule first so it takes priority.
3. Days in a month
days_in_month(m, y) returns 31, 30, 29, or 28 depending on the month and the year. The array holds the standard lengths; February is special-cased to 29 if the year is a leap year. No leap check needed for the other months — they're always the same length regardless of year.
4. The day-count conversion
days_since_epoch(d) sums three parts: all the days from years 1 through d.year - 1, all the days from months 1 through d.month - 1 in d.year, and d.day itself. For 15 August 2023, that's the sum of all days from 1/1/1 to 31/12/2022, plus the days in January through July 2023, plus 15. That's the total.
5. The difference
Once both dates are converted to day numbers, the difference is labs(days_since_epoch(b) - days_since_epoch(a)). labs is the "absolute value for long" from <stdlib.h> — it makes the result positive no matter which date came first. That's why swapping the two dates still gives the same answer.
6. Why not use time.h?
The C standard library does have date functions — mktime, difftime — that handle all this for you. But they have their quirks (time zones, daylight saving, epoch starting at 1970). For a learning exercise, computing the day count yourself is clearer — you can see exactly what the formula is doing. For production code, use time.h. For understanding the concept, use the loop version.
7. What about negative inputs?
If the user enters a negative year or a day outside the month's range, the formula will give nonsense. A real program would validate the input first: year >= 1, month >= 1 && month <= 12, day >= 1 && day <= days_in_month(month, year). For this assignment, assuming valid input is fine, but the validation habit is worth adding next time.
🎯 Remember this: convert each date to days since a fixed start, then subtract. Handle leap years with the 4/100/400 rule. Use labs so the answer is always positive. The rest is just a helper function and two lines in main.
Frequently Asked Questions
1. Why use loops for the day count instead of a formula?
Because the loop version is easier to read and check. A closed-form formula exists (using integer arithmetic with the year, month, and day) but it's a wall of symbols and it's easy to get an off-by-one somewhere. The loop version is O(year) — for years up to 9999, that's a few thousand iterations, which runs instantly on any modern machine. If you ever needed this for millions of dates per second, you'd switch to the formula. For teaching, the loop is the right choice.
2. Why labs instead of abs?
Because the difference between two day counts is a long, and abs works on int. labs is the long version, from <stdlib.h>. If your day numbers stay within INT_MAX (which they do for any realistic year), you could cast to int and use abs. But it's cleaner to keep everything as long and use labs.
3. What about leap years — how does the code handle them?
The is_leap function returns 1 for leap years. In days_since_epoch, the first loop adds 366 for leap years and 365 otherwise. In days_in_month, February returns 29 if the year is a leap year. So leap years are handled automatically — you don't have to do anything special at the call site. The 4/100/400 rule is fully implemented.
4. What if I enter a date before year 1?
The formula assumes year ≥ 1. If the user enters year 0 or a negative year, the loops don't run correctly and the result is wrong. In a real program, you'd validate the year: if (d.year < 1) { error }. For this teaching example, assuming valid years (1 to 9999) is fine.
5. Can I get the difference in months or years instead of days?
Yes, with a bit more work. For months, you'd count whole months between the two dates, then add the leftover days. For years, similar — count whole years, then the leftover months and days. Both are more complex than days, because "a month" isn't a fixed length. Many people just compute the difference in days and divide by 30.44 (average days per month) or 365.25 (average days per year) for a quick approximation. For exact months and years, you'd need a more careful calculation.
6. How does this compare to using time.h?
time.h provides mktime, which converts a struct tm to a time_t (seconds since 1970), and difftime, which subtracts two time_t values. You'd fill a struct tm for each date, call mktime, then difftime, then divide by 86400 to get days. It handles leap years and calendar quirks automatically. It's more robust than our manual code, but it also has its own quirks (time zones, 1970 as the epoch). For learning, the manual version teaches the underlying logic; for production, use time.h.
💡 Tip: After this, try printing the difference in all three units — days, weeks (days / 7), and years (days / 365.25, as a float). Try computing the age of a person from their birthdate to today — same code, just fill one date with time.h's current date. And try handling the case where the user enters an invalid date (Feb 30) — you'll need to check that the day doesn't exceed days_in_month.