Calculating Date Differences

You have two dates (either in your code or in your database columns). How to calculate the difference between them in years, months, weeks etc!

This is one of the most common questions on many forums, and the logic in general is quite simple. Most programming languages give you the ability to get "epoch times" (number of seconds/millioseconds since Jan 1, 1970) from a date. Once you have these for both the dates, you get the difference in number of seconds. Then you can simply divide this number by the number of seconds in each day (60*60*24) to get the number of days between the two dates, and so on.

Please note however that as a rule of thumb, if you intend to perform these calculations on values from database columns, you should consider calculating within the database itself as that may be the fastest and most efficient way of doing it. Below are some examples for popular databases and PHP. The PHP logic should be applicable to many programming languages unless they already provide handy in-built functions.

MS EXCEL

This method does not use the day of the month in its calculations. For example, given a start date of 10/31/00 (EDate) and an end date of 11/2/00 (LDate), one month is returned even though only two days elapsed.

NOTES

A. The two dates are inside the mktime functions in the first line. Just for your reference, format of mktime function is as follows:

mktime(HOURS, MINUTES, SECONDS, MONTH, DAY, YEAR)

B. Months difference may not be totally accurate as my code above approximates 4 weeks in a month (think of February etc). However, it should suffice for all practical purposes, try it.

C. For all the differences, if you want precise numbers instead of rounded integers, please remove the "floor()" functions on the calculations. In general though, rounded numbers are what you are perhaps looking for.