464,384 Members | 1,097 Online
Need help? Post your question and get tips & solutions from a community of 464,384 IT Pros & Developers. It's quick & easy.

# Difference between two dates

 P: 1 How i can easly calculate the difference between two dates ? Example : Date 1 = 12 March(3) Date 2 = 24 November(11) Result = 258 days Can anyone give me an example how to do this in C++ ? Btw i don't want to use date functions or something like that.I want to do it with simple math formula.Thank you! Oct 26 '13 #1

The easiest thing is to convert each date to a number of days and then subtract the two converted results.

Most date conversion routines have a minimum date where earlier dates are not allowed. I have used Jan 1, 1970 but any date earlier than any date you expect will work. This is your minimum date.

First, subtract the years in the date to be converted from the years in the minimum date to get years. Multiply the years by 365 and add this to the result.

Second divide the years by 4 to get the leap days and add this to the result.

Third, if the year 2000 is between the minimum date years and the date to be converted years, then subtract 1 from the result because years divisible by 400 are not leap years.

Fourth, if the year on the date to be converted is a leap year (divisible by 4 but not by 400) and the month is earlier than March, then subtract 1 from the result because the leap day in this date has not yet occurred.

Fifth, convert the month in the date to be converted to days and add this amount to the result. Use 28 for February since the leap day calculation was done in converting the years.

Sixth, add the days in the date to be converted to the result.

Seventh, get a result for each date and subtract the results.

You may find using a date conversion function is preferable because it is already written and debugged. But do post again and let me know how you fared on this.