may be this question had been asked, I've searched but still not confident about my problem..
my problem is checking valid date from string
$a='23-June-11'; //valid
$b='Normal String';//invalid
I want to convert $a and $b using strtotime() before I do that, of course i want to validate whether $a or $b is a valid date format
From $a i can get 23, 11 using explode function, but how about 'June'? using function above, 'June' is not numeric
Why not let strtotime()
do the validation?
It will return false
if it's an invalid date.
Otherwise, you'd have to rebuild strtotime()
's functionality in order to do the validation - sounds like a futile (and big) exercise to me.
As an alternative to strtotime
which will accept relative dates such as "yesterday", "last date of next month" and even "-1 year", I propose using strptime
. It's used to parse a date string according to a format that you specify.
In your case, you'd want strptime($date, '%d-%B-%y')
.
Example:
<?php
// Set the locale as en_US to make sure that strptime uses English month names.
setlocale(LC_TIME, 'en_US');
$dates = array(
'23-June-11',
'Normal String'
);
foreach ( $dates as $date )
{
if ( strptime($date, '%d-%B-%y') )
{
echo $date . ' is a valid date' . PHP_EOL;
}
else
{
echo $date . ' is an invalid date' . PHP_EOL;
}
}
Output:
23-June-11 is a valid date
Normal String is an invalid date