You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中特定格式日期转Unix时间戳后比较异常问题求助

Fixing Your PHP Date Comparison Issue

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:27:53