Skip to content

Instantly share code, notes, and snippets.

@imelgrat
Created April 1, 2019 18:43
Show Gist options
  • Save imelgrat/c5f0ac80472cdbf605f04736dc8b5b8f to your computer and use it in GitHub Desktop.
Save imelgrat/c5f0ac80472cdbf605f04736dc8b5b8f to your computer and use it in GitHub Desktop.
Smarty Modifier - Calculate age from birth date
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
* Place this file inside the smarty/libs/plugins directory and invoke as any other modifier (e.g. {$birth_date|calculate_age} )
*/
/**
* Smarty date_format modifier plugin
*
* Type: modifier<br>
* Name: calculate_age<br>
* Purpose: Calculate age based on a given date<br>
* Input:<br>
* - string: date in the YYYY-MM-DD format
*
* @author Ivan Melgrati
* @param string|\DateTime The birth date
* @return int The actual age. If the birthdate is not a DateTime object cannot be converted to one, -1 will be returned
*/
function smarty_modifier_calculate_age($date)
{
$age = 0;
$clean_date = null;
if (is_a($date, 'DateTime')) {
$clean_date = $date;
} else {
if (is_string($date)) {
$dirty_date = new \DateTime(trim($date));
if (is_a($dirty_date, 'DateTime')) {
$clean_date = $dirty_date;
} else {
// Wrong format. Creation date set to null and returns a null result.
$clean_date = null;
}
}
}
if (is_a($clean_date, 'DateTime')) {
$age = date_diff($clean_date, date_create('now'))->y;
}
else
{
$age = -1;
}
return $age;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment