The checkdate() function in PHP is used to validate a Gregorian date, while the date_diff() function calculates the difference between two DateTime objects. These functions are essential when working with date validation and time intervals.
checkdate(month, day, year) returns true or false.date_diff(date1, date2) returns a DateInterval object.
// Validate whether a specific date exists
<?php
$month = 2;
$day = 29;
$year = 2025;
if (checkdate($month, $day, $year)) {
echo "The date is valid.";
} else {
echo "The date is not valid.";
}
?>
Since 2025 is not a leap year, February 29 does not exist. Therefore, checkdate() returns false.
// Calculate the difference between two dates
<?php
$date1 = date_create("2025-12-25");
$date2 = date_create("2025-01-01");
$diff = date_diff($date1, $date2);
echo $diff->format("%R%a days");
?>
The output shows the total number of days between the two dates with a sign indicating which date comes later.
// Display difference in years, months, and days
<?php
$dateA = date_create("2025-03-10");
$dateB = date_create("2025-09-07");
$interval = date_diff($dateA, $dateB);
echo "Difference: " . $interval->format("%y years, %m months, %d days");
?>
checkdate() before saving them.format() with date_diff() to control output.DateInterval format tokens.