I need to calculate ages depended on birthday from a table of customers.
This is my code:
// customer age
function calculate_customer_age($startDate,$endDate){
$endDate=date(m-d-y);
$startDate= $customer['birthday'];
$fromDate= new DateTime($startDate);
$toDate= new DateTime($endDate);
echo $fromDate->diff($toDate)->days;
}
In the last row, I need to echo age calculated depended on retrieve from a table of a customer from MySQL
.
You can use below code in your function, which will calculate age upto today. You can modify $today to use the end date and format you want.
$dateOfBirth = $customer['birthday'];
$today = date("Y-m-d");
$diff = date_diff(date_create($dateOfBirth), date_create($today));
echo 'Age is '.$diff->format('%y');
You had several errors in your calculate_customer_age
function, instead you can use the below code to get the difference in days between two dates:
function calculate_customer_age($startDate, $endDate)
{
$startDate = DateTime::createFromFormat("m/d/Y", $startDate);
$endDate = DateTime::createFromFormat("m/d/Y", $endDate);
return $startDate->diff($endDate)->days;
}
echo calculate_customer_age("11/30/2008", "08/23/2018"); // 3553
Documentation:
There are many errors in your code. There is no need to pass end date in your function. You can use the following code to get the age.
function calculate_customer_age($startDate){
$fromDate = new DateTime($startDate);
$toDate = new DateTime('today');
return $fromDate->diff($toDate)->days;
// or return $fromDate->diff($toDate)->y;
}
echo calculate_customer_age($customer['birthday']);
PHP >= 5.3.0
$from = new DateTime('1970-02-01');
$to = new DateTime('today');
echo $from->date_diff($to)->y;
echo date_diff(date_create('1970-02-01'), date_create('today'))->y;
MySQL >= 5.0.0
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
If you want to calculate customer's age in days, you should do so:
function calculate_customer_age($startDate){
$fromDate= new DateTime($startDate);
$toDate= new DateTime();
$difference = $fromDate->diff($toDate)->days;
return $difference->format('%a');
}
php code
$startDate = '05-01-1988'; // sample start date or dob
$end_Date = '23-08-2018'; // smmple end date
echo calculate_customer_age( $startDate , $end_Date );
php function that returns age -
function calculate_customer_age( $startDate , $endDate ) //function returns age
{
$diff = date_diff( date_create( $startDate ), date_create( $endDate ) );
return $diff->format('%y Years, %m Months, %d Days');
}
Sample Output :
30 Years, 7 Months, 18 Days