In PHP, you can use the following function to calculate age based on year, month, and day of birth:
encapsulated function
function calculateAge($birthday) {
$currentDate = date('Y-m-d');
$birthdayDate = date('Y-m-d', strtotime($birthday));
$age = date_diff(date_create($currentDate), date_create($birthdayDate))->y;
return $age;
}
// 使用示例
$birthday = '1990-05-15';
$age = calculateAge($birthday);
echo "年龄是:".$age;
This function accepts a string parameter $birthday
which should be in format representing year month day of birth eg '1990-05-15'
. The function first gets the current date $currentDate
, and then uses strtotime()
the function to convert the date of birth into a timestamp format and store it in $birthdayDate
the variable. Next, use date_diff()
the function to calculate the time difference between the current date and the date of birth, and extract the year portion of it. Finally, the age is returned to the caller.
Note that this function assumes that the entered year, month, and day of birth is valid and in the same time zone as the current date. If you need more complex date processing or time zone processing, please modify it accordingly according to your specific needs.
date_create
function
date_create
function is a function in PHP used to create date objects. It accepts a string parameter representing the date and time and returns a date object. date_create
Functions have the following properties:
- Time zone:
date_create
The function uses the current system time zone by default to create a date object. You can specify a timezone via an optional parameter when creating a date object, for exampledate_create('2023-07-19', timezone_open('Asia/Tokyo'))
a date object will be created with the Asia/Tokyo timezone. - Date format:
date_create
The date portion of the date object created by the function is parsed and set according to the format of the input string. You can use standard date formats such asY-m-d
(year-month-day) orH:i:s
(hour:minute:second). - Error handling: If the input date string cannot be parsed or is invalid,
date_create
the function will return FALSE. You can use the error reporting settings to check if any parsing errors occurred. - Chaining:
date_create
The function returns a date object that can be used with other date and time functions. You can perform various operations on the created date object, such as getting the year, month, part of the date, adding and subtracting date intervals, etc.
These are date_create
the main properties of functions. By using this function, you can create date objects and perform various operations on them for date and time processing in PHP.
@missingsometimes