756889 visitors has seen the Tim-Carter.com site. Thanks!
374 visitors has seen the Tim-Carter.com site today.
 
 
Search :  
 
>>> Programming >> PHP > Check if string is a date with PHP (This page has been seen 10617 times)

Function to check if string is a valid date with PHP

This is a quick function i wrote, it returns true or false if the string is a date or not
The Code:
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 ); 
    if (checkdate($month, $day, $year)) 
        return TRUE; 
    return FALSE; 
} 

Like (23)
 
Dislike (19)


Keywords for this article:
Check string if date || check is string is a date || validate date string

Post comment

Name:


Comment:

Code Language:

Code:

Here you can paste a code example. It will then be processed by SyntaxHighlighter and formatted for easier readability.
Please remember to select the correct Code Language in the select above so the SyntaxHighlighter can highlight the code properly.




Code:

Please enter the code you see above

What is 2 + 6 =

Submit Comment


Comment submitted by speed16
Submitted date 2014-06-05 10:44:04
Comment:
For prevent strtotime("A") I added preg_match():
Code:
function is_date( $str ){
    $stamp = strtotime( $str ); 
    if (!is_numeric($stamp) || !preg_match("^\d{1,2}[.-/]\d{2}[.-/]\d{4}^", $str)) 
        return FALSE; 
    $month = date( 'm', $stamp ); 
    $day   = date( 'd', $stamp ); 
    $year  = date( 'Y', $stamp ); 
    if (checkdate($month, $day, $year)) 
        return TRUE; 
    return FALSE; 
}

Comment submitted by Bryan
Submitted date 2013-03-29 06:48:07
Comment:
Because strtotime accepts the very liberal date formats: http://www.php.net/manual/en/datetime.formats.php
Make an array of acceptable formats and put it through:

Code:
DateTime::createFromFormat($good_formats, $str)

Comment submitted by C. Lambert
Submitted date 2012-04-26 22:52:48
Comment:
Any explanation for why strtotime("A") returns something like 1335467840 which actually is converted to the current date by this function, and it returns true?

Code:
strtotime("A")

Comment submitted by C. Lambert
Submitted date 2012-04-26 22:50:55
Comment:
strtotime("A")

Code:
Any explanation for why strtotime("A") returns 1335467840 which actually is converted to the current date by this function?



Advertisement by Google