Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is a date

Tags:

php

I have some dynamic date values that I am trying to change to a human-readable format. Most of the strings I get are in the format yyyymmdd, for example 20120514, but some are not. I need to skip the ones that re not in that format, because they may be not dates at all.

How do I add such check to my code?

date("F j, Y", strtotime($str))
like image 907
santa Avatar asked Jan 22 '26 05:01

santa


2 Answers

You could use this function for the purpose:

/**
 * 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

like image 116
heretolearn Avatar answered Jan 24 '26 19:01

heretolearn


For a quick check, ctype_digit and strlen should do:

if(!ctype_digit($str) or strlen($str) !== 8) {
    # It's not a date in that format.
}

You can be more thorough with 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));
}
like image 37
Ry- Avatar answered Jan 24 '26 18:01

Ry-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!