PHP中特定格式日期转Unix时间戳后比较异常问题求助
Hey there! Let's break down why your date check is always triggering the past-date notice.
The problem comes down to how strtotime() interprets your date string. When you pass "18/05/2018", strtotime() defaults to expecting a MM/DD/YYYY format (month first, day second). Since 18 isn't a valid month, strtotime() returns false.
In PHP, when you compare false with an integer like time(), false gets converted to 0—which is always less than the current timestamp. That's why your if condition is always true, and you see the notice every time.
Here's How to Fix It
Instead of relying on strtotime()'s guesswork, use a function that lets you explicitly define the date format you're working with:
Method 1: Use date_create_from_format()
This function parses the date exactly using the format you specify:
$date = "18/05/2018"; // Parse the date using day/month/year format $dateObj = date_create_from_format('d/m/Y', $date); // First check if the date was parsed correctly if ($dateObj === false) { echo '<b>Error:</b> Please enter a valid date in DD/MM/YYYY format.<br>'; } else { $dateUnix = $dateObj->getTimestamp(); if ($dateUnix < time()) { echo '<b>Notice:</b> You cannot specify a date in the past.<br>'; } else { echo 'Great, your date is valid and not in the past!<br>'; } }
Method 2: Use DateTime::createFromFormat() (Object-Oriented Approach)
If you prefer OOP, this works similarly and lets you catch invalid dates with exceptions:
$date = "18/05/2018"; try { $dateObj = DateTime::createFromFormat('d/m/Y', $date); $dateUnix = $dateObj->getTimestamp(); if ($dateUnix < time()) { echo '<b>Notice:</b> You cannot specify a date in the past.<br>'; } else { echo 'Great, your date is valid and not in the past!<br>'; } } catch (Exception $e) { echo '<b>Error:</b> Please enter a valid date in DD/MM/YYYY format.<br>'; }
Key Takeaway
strtotime() is handy for standard date formats, but it's not reliable for region-specific formats like DD/MM/YYYY. By explicitly defining the format during parsing, you avoid ambiguity and ensure your date comparisons work as expected.
内容的提问来源于stack exchange,提问作者Orbie

