What is Date Difference Program in C- C Programming For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Control Statements

Date Difference Program in C

Calculate the gap between two dates in years, months and days using the borrowing technique. Free C tutorial with a real bug, its fix and tested output.

A date difference program in C answers questions such as “how long has this device been running?” or “how old is this record?”. The tricky part is not the subtraction, it is what to do when a day or month in the later date is smaller than in the earlier date. You solve it the same way you solved subtraction on paper in school: by borrowing. In this lecture of our free C programming course you will implement borrowing with if and switch, discover a classic edge case bug and fix it. These skills carry directly into embedded C programming, where uptime counters and timestamps are everywhere.

What You Will Learn

  • Why plain subtraction of day, month and year fields can give negative results.
  • How borrowing works for days (add a month’s days) and for months (add 12).
  • How to pick the correct number of days to borrow with a switch.
  • How a plausible looking solution can still fail on a corner case, and how to find it with tests.
  • How to compare two dates field by field before calculating.

Prerequisites

Finish the previous lecture on date validation first. You need the leap year expression, nested conditions and switch. This program assumes both dates are valid and the first date is not after the second, but we will still add a safety check for the order.

The Idea Behind the Date Difference Program in C

Suppose the earlier date is 15-08-2020 and the later date is 10-10-2026. Subtracting field by field gives years 6, months 2 and days minus 5. A negative day count makes no sense, so we fix it before subtracting.

Borrowing like paper subtraction
Later: 10 – 10 – 2026  Earlier: 15 – 08 – 2020
Day 10 < 15 : borrow one month → day = 10 + 31 = 41, month = 10 – 1 = 9
Month 9 ≥ 8 : no year borrow
Years 2026 – 2020 = 6 Months 9 – 8 = 1 Days 41 – 15 = 26
SituationFixEffect
Later day < earlier dayAdd days of one month to the later day, reduce later month by 1Day difference becomes zero or positive
Later month < earlier monthAdd 12 to later month, reduce later year by 1Month difference becomes zero or positive
Both borrows neededDo the day borrow first, then the month borrowOrder matters because the day borrow can lower the month

A Tempting Version That Fails

Most people borrow from the month just before the later date. For 10-10-2026 that is September with 30 days. It feels natural, and it works for many inputs, but see what happens for 31-01-2024 and 01-03-2024. The previous month of March is February 2024 with 29 days.

/* tempting rule: borrow days of the month before the later date */
d2 = 1 + 29;      /* 30 */
m2 = 3 - 1;       /* 2  */
/* months: 2 - 1 = 1, days: 30 - 31 = -1  */

The output of that version would be:

Gap: 0 years, 1 months, -1 days
Negative days. When the earlier date has day 31 and the borrowed month is shorter, one borrow is not enough. The program is wrong even though it compiles cleanly and works for most dates. This is why testing edge cases is a skill, not an optional extra.

The Fix: Borrow the Earlier Date’s Month

If we borrow the number of days in the earlier date’s month, the borrowed amount is always at least the earlier day number. That guarantees the day difference can never go negative. This is the convention used in the program below: count full months from the earlier date, then the leftover days.

Convention note

Different programs define “one month” slightly differently, so two valid tools may disagree by a day on some inputs. What matters is that your rule is consistent and never produces negative values. Always write the rule you chose in a comment.

Complete Date Difference Program in C

#include <stdio.h>

int main(void)
{
    int d1, m1, y1, d2, m2, y2;
    int days_borrowed;

    printf("Earlier date (dd-mm-yyyy): ");
    if (scanf("%d-%d-%d", &d1, &m1, &y1) != 3) return 1;
    printf("Later date   (dd-mm-yyyy): ");
    if (scanf("%d-%d-%d", &d2, &m2, &y2) != 3) return 1;

    if (y1 > y2 || (y1 == y2 && (m1 > m2 || (m1 == m2 && d1 > d2))))
    {
        printf("First date must not be after the second date\n");
        return 1;
    }

    if (d2 < d1)                     /* borrow days */
    {
        switch (m1)                  /* length of the earlier month */
        {
        case 2:
            days_borrowed = ((y1 % 4 == 0 && y1 % 100 != 0) || y1 % 400 == 0) ? 29 : 28;
            break;
        case 4: case 6: case 9: case 11:
            days_borrowed = 30;
            break;
        default:
            days_borrowed = 31;
        }
        d2 += days_borrowed;
        m2 -= 1;
    }

    if (m2 < m1)                     /* borrow a year */
    {
        m2 += 12;
        y2 -= 1;
    }

    printf("Gap: %d years, %d months, %d days\n", y2 - y1, m2 - m1, d2 - d1);
    return 0;
}

Build and Run

gcc -Wall -Wextra -std=c11 -o date_diff date_diff.c
./date_diff
EarlierLaterOutput
15-08-202010-10-2026Gap: 6 years, 1 months, 26 days
31-01-202401-03-2024Gap: 0 years, 1 months, 1 days
25-12-202505-01-2026Gap: 0 years, 0 months, 11 days
10-05-202010-05-2020Gap: 0 years, 0 months, 0 days
28-02-202301-03-2023Gap: 0 years, 0 months, 1 days

Reading the Code Step by Step

  1. Read both dates and stop if either scanf fails to read three numbers.
  2. Order check. The long condition compares year first, then month if years are equal, then day if months are equal. It is a lexicographic comparison, exactly like comparing words letter by letter.
  3. Day borrow. Only when the later day is smaller. The switch on m1 chooses 28, 29, 30 or 31.
  4. Month borrow. Runs after the day borrow, because the day borrow may have reduced m2 below m1.
  5. Final subtraction. Years, months and days are now all zero or positive.
Program flow
Read two dates → Order OK? → d2 < d1 ? → Yes : switch(m1), add days, m2 – 1
m2 < m1 ? → Yes : m2 + 12, y2 – 1 → Subtract and print

Another Approach: Count Total Days

There is a completely different technique. Convert each date into a count of days since a fixed starting point, subtract the two counts and print the difference in days. It avoids borrowing, but turning the days back into years and months brings the same convention question. Embedded systems often prefer this method for uptime: store one counter and format it only when displaying.

ApproachStrengthWeakness
Borrowing (this lecture)Direct years / months / days answer, no large numbersEdge cases need care
Total day countExact day difference, easy to compare datesNeeds extra step to show months and years

Common Mistakes and Troubleshooting

  • Borrowing a month without reducing m2. The month you borrowed must disappear from the later date or the answer is one month too large.
  • Doing the month borrow before the day borrow. The day borrow changes m2, so the month check must come second.
  • Using the wrong year for February. The year of the borrowed month decides 28 or 29. Here it is y1, the earlier date’s year.
  • Skipping the order check. Reversed dates produce negative years that look like valid output.
  • Never testing 31st dates. Always include inputs like 31-01 and 30-03 when you test month arithmetic.
  • Forgetting validation. This program assumes valid dates. In real code run the validation from the previous lecture first.

Best Practices and Considerations

  • Write down the rule you chose in a comment above the borrowing block.
  • Test with at least one case for each branch: no borrow, day borrow, month borrow and both.
  • Use integer types only; there is no reason for floating point here.
  • Performance: the program does a fixed number of comparisons, so it runs in constant time regardless of how far apart the dates are.
  • Security and safety: in firmware, never let a negative duration reach a timer or delay function. Check order and range first.

Real-World Uses

  • Showing device uptime or time since last calibration in a diagnostics screen.
  • Warranty and licence expiry calculations.
  • Age calculators in forms and databases.
  • Scheduling and maintenance reminders in industrial controllers.

Summary and Key Takeaways

  • Subtract field by field, but fix negative days and months by borrowing first.
  • Do the day borrow before the month borrow.
  • Borrowing the earlier date’s month length prevents negative days.
  • Edge case testing found a bug that normal inputs never showed.

Next we leave calendars and look at a surprisingly old multiplication trick that needs only halving, doubling and addition, perfect for processors without a multiply instruction. Stay with this free embedded C course to see it work.

Frequently Asked Questions

Why can the same two dates give different answers in different tools?

Months have unequal lengths, so tools choose different conventions for what a month means. Pick one rule and document it.

Why borrow days before borrowing months?

Borrowing days lowers the later month by one. The month check must see that updated value.

Is the 29th February handled correctly?

Yes, the switch uses the leap year test on the earlier year when February is the borrowed month.

Can I get the difference in total days instead?

Yes. Convert each date to a day count since a reference date and subtract. It is a good exercise after you learn arrays.

What if the first date is after the second?

The order check prints an error and stops, preventing negative output.

Where does this matter in embedded C programming?

Any device that logs time, tracks uptime or schedules maintenance needs reliable date arithmetic.

Learn Embedded C for Free

Follow the full EmbeddedPathashala free C tutorial and build the problem solving habits that embedded engineers use every day.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →