What are some common methods for validating and formatting birthdates in PHP to ensure accurate age calculations?

When working with birthdates in PHP, it is important to validate the input to ensure accurate age calculations. One common method is to use the DateTime class to parse and validate the input date. Additionally, formatting the birthdate in a standard format (e.g., YYYY-MM-DD) can help ensure consistency and accuracy in age calculations.

// Validate and format a birthdate in PHP
$birthdate = '1990-12-31';

// Validate the birthdate format
if (DateTime::createFromFormat('Y-m-d', $birthdate) !== false) {
    // Format the birthdate in a standard format
    $birthdate = date('Y-m-d', strtotime($birthdate));
    
    // Perform age calculation using the birthdate
    $dob = new DateTime($birthdate);
    $now = new DateTime();
    $age = $now->diff($dob)->y;
    
    echo "Age: " . $age;
} else {
    echo "Invalid birthdate format";
}