检查字符串是否为日期

时间:2012-08-28 18:22:48

标签: php

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

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

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

3 个答案:

答案 0 :(得分:7)

您可以将此功能用于此目的:

/**
 * 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);
}

@source

答案 1 :(得分:4)

要快速检查,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));
}

答案 2 :(得分:-1)

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

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