2012-08-28 147 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)',請爲上帝的愛使用大括號! –

相關問題