Encapsulated function to calculate age based on date of birth in PHP

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 $birthdaywhich 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 $birthdayDatethe 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_createfunction

date_createfunction 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_createFunctions have the following properties:

  1. Time zone: date_createThe 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 example date_create('2023-07-19', timezone_open('Asia/Tokyo'))a date object will be created with the Asia/Tokyo timezone.
  2. Date format: date_createThe 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 as Y-m-d(year-month-day) or H:i:s(hour:minute:second).
  3. Error handling: If the input date string cannot be parsed or is invalid, date_createthe function will return FALSE. You can use the error reporting settings to check if any parsing errors occurred.
  4. Chaining: date_createThe 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_createthe 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

Guess you like

Origin blog.csdn.net/weixin_41290949/article/details/132632397