Skip Navigation

[Resolved] Returning Age (years and Months) from birthdate

This support ticket is created 5 years, 6 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 1 reply, has 2 voices.

Last updated by Christian Cox 5 years, 6 months ago.

Assisted by: Christian Cox.

Author
Posts
#1275769

Similar to this thread https://toolset.com/forums/topic/calculate-age-from-date-of-birth-custom-filed/ I am trying to return an age from a date. This solution works perfectly for returning the age in years. Is there a solution available for returning Years and months. So if someone is 1 years/2 months or 2 years/6 months.

add_shortcode( 'time_ago', 'time_ago_func');
function time_ago_func($atts){
global $wpdb;
extract( shortcode_atts( array(
'birthdate' => '',
), $atts ) );

//explode the date to get month, day and year
//$birthDate = explode("-", $birthDate);
//get age from date or birthdate
//$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? ((date("y")-$birthDate[2])-1):(date("Y")-$birthDate[2]));
$age = floor((time() - $birthdate)/(365*24*60*60));
return $age;
}

And then to return....
[time_ago birthdate='[types field="model-birthdate" raw="true" id=""][/types]']

#1275871

Here's an updated shortcode:

/* ----------------------------------------------------------------------- */
// DIFFERENCE BETWEEN TWO DATES
// Supply a start and end date, and an optional 0 string
// ex. [format_date_difference start="1994-01-01" end="" format="%y years"]  // 25 years
// ex. [format_date_difference start="1994-01-01" end="2010-05-31" format="%y years"]  // 16 years
// ex. [format_date_difference start="1994-01-01"]  // 23  years, 8 months, 18 days 
// ex. [format_date_difference] // 0 years, 0 months, 0 days
add_shortcode( 'format_date_difference', 'format_date_difference_func');
function format_date_difference_func($atts = [])
{
  $atts = shortcode_atts([
    'start' => '',
    'end' => '',
    'format' => '%y years, %m months, %d days',
  ], $atts);
  $datetime1 = new DateTime($atts['start']);
  $datetime2 = new DateTime($atts['end']);
  $interval = $datetime1->diff($datetime2);
  return $interval->format($atts['format']);
}

For years/months, use the format string "%y years/%m months" like this:

[format_date_difference start="1994-01-01" end="" format="%y years/%m months"][/format_date_difference]