0

I have the following SQL query and I would like to output the ageOnLastSeptember date in a UK (dd/mm/yyyy) format. Can anyone tell me how I can achieve this?

$sql="select ( if(month(now()) < 9, year(now()) - 1, year(now())) - year(dob) - if(month(dob)<9, 0, 1)  ) as ageOnLastSeptember,first_name,last_name,dob,school,contact_no,family_id,contact_id from members_family where contact_id = '$contact_id' ";

I tried the following but it did nothing

$sql="select date_format(( if(month(now()) < 9, year(now()) - 1, year(now())) - year(dob) - if(month(dob)<9, 0, 1)  ), '%d/%m/%Y') as ageOnLastSeptember,first_name,last_name,dob,school,contact_no,family_id,contact_id from members_family where contact_id = '$contact_id' ";

3 Answers3

2

You do not need to do formatting at the database level. If you have dates stored as dates (the correct way), just get the records and send it to the client. Formatting should be done at the control which you are using to display these dates.

danish
  • 5,550
  • 2
  • 25
  • 28
2

I think it will much easier and better to format the date using PHP rather than formatting using MySQL. After retrieving the data from MySQL you can format using PHP like

$date = date("d/m/Y", strtotime('2002-05-18'));

The output will be : 18/05/2002

So your PHP code will be :

<td>". date("d/m/Y", strtotime($rows['dob'])) ."</td> 

More info on PHP date and its format can be found here: http://php.net/manual/en/function.date.php

Hope this helps you :)

Sabari
  • 6,205
  • 1
  • 27
  • 36
0

Not sure how an age can be formatted as a DD/MM/YYYY date. Doesn't seem logical

To get the age in days you could use something like the following

SELECT FLOOR(NOW(), DATE_ADD(dob, INTERVAL (ABS(DATEDIFF(CONCAT(YEAR(DATE_ADD(NOW(), INTERVAL -8 MONTH)),':09:01'), NOW())) * -1) DAY)) AS Age
FROM members_family 
WHERE contact_id = '$contact_id'

That could be customised to give an age in years (gets a bit trickier to be 100% accurate with leap years, especially if you want to cope with every 100th year not being a leap year but every 400th year being a leap year)

Kickstart
  • 21,403
  • 2
  • 21
  • 33