2012-08-28 148 views
3

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

如何将这种检查添加到我的代码中?

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

不太明白你的意思,你想检查你得到的字符串是否是YYYYMMDD格式?或者你想确保它不是? –

回答

-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”? :) –

+1

为什么?比正则表达式更简单(也更有效)。 –

+4

@ZoltanToth:嘿,也许在8745年,会有95个月。为什么不? :-P –

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

可以简化为'返回checkdate($ month,$ day,$ year)',请为上帝的爱使用大括号! –

相关问题