I am trying to calculate the differences between 2 dates.
The first date is the reservation date, and the second date is the traveler's birthdate. Format of the $tour_day is 15 December, 202X
$date1 = new DateTime($bir_day);
$date2 = new DateTime($tour_day);
$interval = $date1->diff($date2);
if( ($interval->y <= 8 && ($interval->m > 12 || $interval->d > 31)) || ($interval->y < 8) ){
// error: Adults must be at least 8 years old
}
It works if the reservation date is the current year.
However if the reservation date is 2022 or more, than it cannot calculate correctly because
$date2 = new DateTime($tour_day);
is always converts as 2021.
echo $tour_day;
is '15 December, 2023' But
echo $date2->format('m-d-y');
is '12-15-21' however it must be '12-15-23' (12-15-23 is what I want but it shows 12-15-21)
I do not understand why the future date (next year or more) is not converting correctly but the current year of any date is no problem.
CodePudding user response:
that's because your date string is not in proper format as required by DateTime, use createFromFormat() as:
...
$tour_day = "5 December, 2023";
// your format is "Day Month, Year", so use that format as below
$date2 = DateTime::createFromFormat("j F, Y", $tour_day);
echo $date2->format('m-d-y'); // 12-05-23
...