Hello guys, How could I calculate an person's age if I have their year of birth? Im trying this function: function age_in_years() { global $postmeta; $year_of_birth = get_field( "date_of_birth",$modelID); $date1 = strval( $year_of_birth ); $date2 = strval( date( 'yy') ); $age = $date2 = $date1; return $age; } PHP: But is not working at all... what I am doing wrong? Using this code: <?php echo age_in_years();?> PHP: Is getting this: 05/07/1992 Code (markup): Database screenshot: http://i.imgur.com/mjLrEQx.png Waiting for your help, thanks Thanks heaps Tim
Have you tried doing it the classic php way $from =newDateTime('1970-02-01'); $to =newDateTime('today'); echo $from->diff($to)->y; PHP:
Thank you for your reply and help sarahk Yeah, you are right... that can work! But maybe you can hep me... If I have this code to calculate age: <?php echo date_diff(date_create('04-08-1967'), date_create('today'))->y; ?> PHP: And If I have this one to get the birth date: <?php echo get_field( "date_of_birth",$modelID); ?> PHP: I need to replace the '04-08-1967' of 1st code with the 2nd code right? But how can I do that? My php knowledge is very poor... I tried: <?php echo date_diff(date_create('get_field( "date_of_birth",$modelID);'), date_create('today'))->y; ?> PHP: But without success... Im doing something wrong... help Thanks!!
for starters, it's seen as a good thing to have code all on one line but if you have to maintain it later it can be a nightmare. Add to that the fact that you are just learning and it can make really good sense to have several lines So I'd do <?php $dob = get_field( "date_of_birth",$modelID); $datedob = date_create($dob); $today = date_create('today'); echo date_diff($datedob, $today)->y; ?> PHP: ** untested **
As a side note, the reason your code didn't work was that you tried putting a function call inside quotes. The idea was pretty close to correct, but the right code would be as this: <?php echo date_diff(date_create(get_field( "date_of_birth",$modelID)), date_create('today'))->y; ?> PHP: Colored editors should help you here, since they usually have their own color for text inside quotes (strings) and functions, and so on.