将月份从名称转换为数字

asl*_*lum 48 php time

有一个简单的方法来改变$month = "July";,这样$nmonth = 7 (07就可以了太).我可以做一个案例陈述,但肯定有一个转换功能?编辑:我希望我能接受多个答案,因为你们两个人基本上都给了我所需要的力量.

$nmonth = date('m',strtotime($month));
Run Code Online (Sandbox Code Playgroud)

这将给出数值$month.谢谢!

Mat*_*hew 72

试试这个:

<?php
  $date = date_parse('July');
  var_dump($date['month']);
?>
Run Code Online (Sandbox Code Playgroud)

  • 这也适用于缩写形式“ Jan”,“ Jul”,“ Oct”等。 (4认同)

Sar*_*raz 64

是,

$date = 'July 25 2010';
echo date('d/m/Y', strtotime($date));
Run Code Online (Sandbox Code Playgroud)

m格式一个月的数字表示在那里.


VKG*_*KGS 18

这里有一个有趣的外观,凯利给出的代码效果很好,

$nmonth = date("m", strtotime($month));
Run Code Online (Sandbox Code Playgroud)

但是对于2月份,当闰年为30或31,非闰年为29,30,31时,将无法按预期工作.月份数将返回3.例如:

$nmonth = date("m", strtotime("february"));
Run Code Online (Sandbox Code Playgroud)

解决方案是,将月份添加为月份,如下所示:

$nmonth = date("m", strtotime("february-2012"));
Run Code Online (Sandbox Code Playgroud)

我从php手册中的这个评论中得到了这个.


Vin*_*kal 11

$string = "July";
echo $month_number = date("n",strtotime($string));
Run Code Online (Sandbox Code Playgroud)

返回'7'[月号]

使用date("m",strtotime($string));的输出"08"

欲了解更多格式,请访问
http://php.net/manual/en/function.date.php


小智 5

你也可以用这个:

$month = $monthname = date("M", strtotime($month));
Run Code Online (Sandbox Code Playgroud)