Friday, June 7, 2013

Calculate How Many Year, Month And Day Passed On Given Date Using MySQL

PROBLEM

How to calculate how many year, month and Day passed on given date using MySQL.

SOLUTION

Calculating how many years, month and date passed on a given date in MySQL is easy, you only need to use division, modulo and TIMESTAMPDIFF function (see the query below).

SELECT TIMESTAMPDIFF(YEAR, '2012-01-17', '2013-06-07') AS year_passed,
              TIMESTAMPDIFF(MONTH, '2012-01-17', '2013-08-10') MOD 12 AS month_passed,
              TIMESTAMPDIFF(DAY, '2012-01-17', '2013-06-07') MOD 365 AS day_passed