Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check that the given string is a valid month or not?

Tags:

php

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.

like image 620
Sam Avatar asked Oct 29 '25 14:10

Sam


1 Answers

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

like image 79
Mark Baker Avatar answered Oct 31 '25 05:10

Mark Baker



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!