将短格式月份名称转换为月份号码

时间:2015-12-31 09:30:02

标签: php

$month_name = 'Feb';
$month_number = date("m", strtotime($month_name));

从上面的代码中,我得到的输出是03而不是02.为什么?

5 个答案:

答案 0 :(得分:1)

我想这是由strtotime函数中日期的当前日期和默认值引起的。今天我们有12月31日所以如果您使用strtotime,日期的默认值将是2015年12月31日,但如果您将月份更改为2月,则日期将是2015年3月3日。此处的解决方案是在开头添加第一天的数字,例如

$month_name = '1 Feb';
$month_number = date("m", strtotime($month_name));

答案 1 :(得分:1)

您可以使用date_parse()

功能
$month_name = 'Feb';
$date = date_parse($month_name);
echo $date['month'];

答案 2 :(得分:1)

这样的......简单的方法......

$mons = array("Jan" => 1, "Feb" => 2, "Mar" => 3, "Apr" => 4, "May" => 5, "Jun" => 6, "Jul" => 7, "Aug" => 8, "Sep" => 9, "Oct" => 10, "Nov" => 11, "Dec" => 12);    
$month_name = 'Feb';    
$month_number = $mons[$month_name];

答案 3 :(得分:0)

strtotime不会那样运作。您可以在PHP手册中查看。您可以在此处使用date_parse

$month = 'Feb';
$month = date_parse($month);
echo $month['month'];

此函数将返回如下数组:

Array
(
    [year] => 
    [month] => 2
    [day] => 
    [hour] => 
    [minute] => 
    [second] => 
    [fraction] => 
    [warning_count] => 1
    [warnings] => Array
        (
            [4] => The parsed date was invalid
        )

    [error_count] => 0
    [errors] => Array
        (
        )

    [is_localtime] => 
)

现在,您可以获取月份名称或其他任何内容。

或者,您仍然希望使用strtotime功能,而不是尝试:

$month = '1 Feb';
$month = date("m",strtotime($month));
echo $month;

答案 4 :(得分:0)

您应该按如下方式传递完整日期:

$month_name = 'Feb';
$month_number = date("m", strtotime("1-".$month_name."-2015"));
相关问题