标签:php
我正在执行一个检查月份是否有效的功能.
例如.
checkMonth("Feb") => true
checkMonth("Mar") => true
checkMonth(02) => true
checkMonth(2) => true
但
checkMonth("X") => false
checkMonth("XYZ") => false
数字形式2或02没有问题.
但是,如果我传递“ X”或“ XYZ”之类的参数,则无法正常工作并返回true.
我正在努力
echo date('n', strtotime("XYZ"));
由于date(‘n’,strtotime(“ XYZ”))的值为3(即有效月份),因此返回true.
我也试过
$mon=date_format(date_create("XYZ"),"n");
但是它具有相同的影响.
解决方法:
$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;
(仅适用于英语名称达数月)
标签:php
来源: https://codeday.me/bug/20191120/2045304.html