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))
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
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With