I'm making a function to check the month is valid or not. For eg.
checkMonth("Feb") => true
checkMonth("Mar") => true
checkMonth(02) => true
checkMonth(2) => true
But
checkMonth("X") => false
checkMonth("XYZ") => false
There is no issue in the numeric form 2 or 02. But if I'm passing argument like "X" or "XYZ" its not working and returns true.
Im trying
echo date('n', strtotime("XYZ"));
which is returning true because the value of date('n', strtotime("XYZ")) is 3 which is a valid month.
I also tried
$mon=date_format(date_create("XYZ"),"n");
But it has the same affect.
You can create your own function and setup an array that holds the 1,2,3,4 and 01,02,03 and jan,feb,march and then in your function you check if string exists in the array, then return true :)
Go for it! :D
EDIT: if you want to make it cooler you can make a preg_match... but is a little bit trickier :P
EDIT 2: you can use checkdate: http://php.net/manual/en/function.checkdate.php
<?
date_default_timezone_set('UTC');
echo strtotime('xyz');
?>
Gives me null value and Prints true!
You could have a function like
<?
function isMonthString(month) {
if(strtotime(month) == null)
return False;
return date("n", strtotime(month));
}
?>
Please note that my php is a bit hazy so the syntax might be wrong.
This function from the PHP manual seems to do the trick
<?
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
?>
$month = 'XYZ';
$x = DateTime::createFromFormat('M', $month);
if (!$x) {
die($month . ' is not a valid month');
}
echo $month, 'is month number ', $x->format('n'), PHP_EOL;
(only works with English language names for months)