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]']
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]