简体   繁体   English

新的 DateTime 不能与未来的日期一起正常工作

[英]new DateTime is not working properly with the future date

I am trying to calculate the differences between 2 dates.我正在尝试计算 2 个日期之间的差异。

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 $tour_day 的格式为 202X 年 12 月 15 日

$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但是,如果预订日期为 2022 年或以上,则无法正确计算,因为

$date2 = new DateTime($tour_day);

is always converts as 2021.始终转换为 2021。

echo $tour_day; 

is '15 December, 2023' But是 '2023 年 12 月 15 日' 但是

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)是 '12-15-21' 但它必须是 '12-15-23' (12-15-23 是我想要的,但它显示 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.我不明白为什么未来日期(明年或更多)没有正确转换,但任何日期的当前年份都没有问题。

that's because your date string is not in proper format as required by DateTime , use createFromFormat() as:那是因为您的日期字符串的格式不符合DateTime的要求,请使用createFromFormat()作为:

...
$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
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM