# C Program to calculate the difference of two dates in years, months and days

The following is a C program to calculate the difference of two dates in years, months and days. Make sure that the start date is earlier than the end date.

Expected Output:

1st run:

2nd run:

## How it works

The process of calculating the difference of two dates in terms of years, months and days is quite simple. All we need to do is subtract day, month and year of the start date from the day, month and year of the end date, respectively.

Note that here we are assuming that the start date is smaller than the end date and the difference of days, months and years will be positive.

However, there is one problem.

What if the difference of days and months isn’t positive?

For example, consider the following two dates:

In this case, the first date is smaller than the second, but the difference in days and months is not positive.

To handle cases like this we do the following:

If `day2 < day1`, we borrow a month that is before `mon2` and add days in that month to `day2`. For example, if `mon2 == 09` i.e September, then we borrow month August month and add days in August to `day2`.

`day2 = day2 + 30`. (there are 30 days in August)

Also, since we are borrowing a month we have to subtract `1` from `mon2`.

`mon2 = m2 - 1`

Similarly, If `mon2 < mon1`, then we borrow one 1 year i.e 12 months and add that many months to `mon2`.

`mon2 = mon + 12`

Again, just as with months, we have to subtract `1` from the `year`.

`year2 = year2 - 1`