Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate age in months and years OR format seconds as years and months?

Tags:

mysql

I need to find out the age of a person at a certain point in time. I've got both the DOB and this 'point in time' as unix timestamps.

I could subtract them to get their age in seconds at that time, but... I don't see any MySQL functions to format it into years and months.

How can I do that?

Specifically, the format I want is 5y 6m.

like image 467
mpen Avatar asked Jun 23 '11 17:06

mpen


2 Answers

SELECT CONCAT(    
  YEAR(DATE_ADD('2000-01-01',INTERVAL (DATEDIFF(FROM_UNIXTIME(tpit), FROM_UNIXTIME(dob))) DAY))-2000, 'y ',
  MONTH(DATE_ADD('2000-01-01',INTERVAL (DATEDIFF(FROM_UNIXTIME(tpit), FROM_UNIXTIME(dob))) DAY)), 'm'
  ) as output 
FROM ..... WHERE .....
like image 200
Johan Avatar answered Oct 30 '22 14:10

Johan


This is your query:

SELECT CONCAT(
    TIMESTAMPDIFF(YEAR, FROM_UNIXTIME(`dob`), FROM_UNIXTIME(`point_in_time`)), 
    'y ',
    MOD(TIMESTAMPDIFF(MONTH, FROM_UNIXTIME(`dob`), FROM_UNIXTIME(`point_in_time`)), 12),
    'm'
) `age`
...
...

Another one might be:

SELECT CONCAT(
    FLOOR((`point_in_time` - `dob`) / 31536000),
    'y ',
    FLOOR(MOD((`point_in_time` - `dob`) / 31536000 * 12, 12)),
    'm'
) `age`
...
...

Hope this helps?

like image 2
Abhay Avatar answered Oct 30 '22 16:10

Abhay