3

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.

Apul Gupta
  • 3,044
  • 3
  • 22
  • 30
Sam
  • 41
  • 2
  • 13

3 Answers3

3
$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)

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
1

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

Medda86
  • 1,582
  • 1
  • 12
  • 19
  • That can be one way of doing it. But isn't there any function in php that can check the string is valid month or not? – Sam Mar 13 '15 at 07:57
  • 1
    @Sam, check my 2nd edit, checkdate is probably what you looking for – Medda86 Mar 13 '15 at 08:02
  • Im using checkdate() thats why i need to convert string month into numeric because it takes all numeric arguments. – Sam Mar 13 '15 at 08:32
0
<?
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;
}
?>

function was copied from this answer or php.net

Community
  • 1
  • 1
Prathik Rajendran M
  • 1,152
  • 8
  • 21