检查一个字符串是否为日期

3

我有一些动态日期值,我想把它们改成易于阅读的人类格式。 我得到的大多数字符串都是以 yyyymmdd 格式为例,例如20120514,但有些不是。 我需要跳过那些不符合该格式的日期,因为它们可能根本不是日期。

如何在我的代码中添加这样的检查?

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

1
你的意思我不太明白,你是想检查获取到的字符串是否为YYYYMMDD格式吗?还是想确认它不是这种格式? - Madara's Ghost
3个回答

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


4
可以简化为 return checkdate($month, $day, $year),请务必使用花括号! - Madara's Ghost

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

-1
我会使用正则表达式来检查字符串是否有8个数字。
if(preg_match('/^\d{8}$/', $date)) {
    // This checks if the string has 8 digits, but not if it's a real date
}

1
如果字符串是 87459235 呢? :) - Zoltan Toth
1
为什么?比正则表达式更简单(且更高效)的方法是存在的。 - Madara's Ghost
4
嗨,也许在8745年会有95个月份。为什么不呢? :-P - gen_Eric
1
@Rocket,相信你的脚本在8745年仍然有用是非常乐观的 :) - Zoltan Toth
1
真的,我在想要检查这些字符是否是数字...上面的答案也会有同样的问题吗? - marc_ferna
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接