【问题标题】:PHP convert short month-name to month-number [duplicate]PHP将短月份名称转换为月份编号[重复]
【发布时间】:2011-06-04 11:27:42
【问题描述】:

可能重复:
convert month from name to number

我有一个简单(但有趣)的查询。

我得到月份名称,简而言之,例如 Jan、Feb 等。现在我需要将其转换为月份数(即月份的数字表示),带有前导零

例如:“Jan”到“01”,“Dec”到“12”等

任何人都知道,如何实现这一点,不使用数组

谢谢

【问题讨论】:

  • 为什么不用数组?
  • @StasM:我需要看看一个东西可以变得多么复杂,我知道使用数组,它只是“蛋糕”,但其他任何方式都是如此。

标签: php


【解决方案1】:
$month = 'Feb';
echo date('m', strtotime($month));

strtotime 将“Feb”转换为 February 6th 2011 15:15:00 的时间戳(在撰写本文时),从给定的字符串中提取并填写空白从当前时间开始。 date('m') 然后格式化这个时间戳,只输出月份数。

由于这实际上可能会在 31 日引起问题,因此您应该填写这些空白以确保:

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

【讨论】:

    【解决方案2】:
    $date = strtotime ("Jan");
    print date("m", $date);
    

    更多关于strtotime:PHP: strtotime - Manual

    更多信息:PHP: date - Manual

    【讨论】:

    • 这不适用于 PHP 7。'Feb' 和 'Mar' 都返回 03。
    【解决方案3】:

    试试这个

    $test  //whatever you getting
    echo date("m",strtotime($test));
    

    另见

    http://php.net/manual/en/function.date.php

    【讨论】:

      【解决方案4】:

      将它与一天和一年一起使用它会很好地隐藏:

      $mon = 'Feb';
      $month = date("F d Y",strtotime("$mon 31, 2010"));
      

      它会正常工作的。

      【讨论】:

        【解决方案5】:

        strtotime 可以解决问题。

        例如:

        $monthName = 'Jan';
        
        echo date('m', strtotime($monthName));
        

        【讨论】:

        • 这不适用于 PHP 7。'Feb' 和 'Mar' 都返回 03。
        【解决方案6】:

        鉴于你已经有了约会对象。

        $date = 'Jun';
        $month = date('m', strtotime($date));
        

        【讨论】:

        • 这不适用于 PHP 7。'Feb' 和 'Mar' 都返回 03。
        【解决方案7】:

        这对我不起作用:

        $mon = 'Aug';
        $month = date("F",strtotime($mon));
        

        我得到“十二月”???

        但是,如果我将其与日期和年份放在一起,它会很好地转换:

        $mon = 'Aug';
        $month = date("F d Y",strtotime("$mon 31, 2011"));
        

        它有效。

        运行 PHP 5.1.2 版

        【讨论】:

          猜你喜欢
          • 2011-06-04
          • 1970-01-01
          • 2021-10-03
          • 1970-01-01
          • 1970-01-01
          • 2019-12-26
          • 2012-08-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多