Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

new DateTime is not working properly with the future date

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading