检查字符串是否为日期


Check if a string is a date

我有一些动态日期值,我正试图将其更改为可读格式。我得到的大多数字符串的格式是yyyymmdd,例如20120514,但有些不是。我需要跳过那些不是那种格式的,因为它们可能根本不是日期。

如何将此类检查添加到代码中?

date("F j, Y", strtotime($str))

您可以将此函数用于以下目的:

/**
 * Check to make sure if a string is a valid date.
 * @param $str   String under test
 *
 * @return bool  Whether $str is a valid date or not.
 */
function is_date($str) {
    $stamp = strtotime($str);
    if (!is_numeric($stamp)) {
        return FALSE;
    }
    $month = date('m', $stamp);
    $day   = date('d', $stamp);
    $year  = date('Y', $stamp);
    return checkdate($month, $day, $year);
}

@源

为了进行快速检查,ctype_digitstrlen应该执行以下操作:

if(!ctype_digit($str) or strlen($str) !== 8) {
    # It's not a date in that format.
}

使用checkdate:可以更彻底

function is_date($str) {
    if(!ctype_digit($str) or strlen($str) !== 8)
        return false;
    return checkdate(substr($str, 4, 2),
                     substr($str, 6, 2),
                     substr($str, 0, 4));
}

我会使用正则表达式来检查字符串是否有8位数字。

if(preg_match('/^'d{8}$/', $date)) {
    // This checks if the string has 8 digits, but not if it's a real date
}