PHP:将本地monthname转换为monthnumber


PHP: Convert local monthname to monthnumber

如何将月份的本地名称转换为相应的月份编号?

你可以手动进行翻译,但我敢肯定PHP有一些内置的函数吗?

$monthname = "februar"; // norwegian name for february
$monthnumber = insertCorrectFunctionHere($monthname);

目标是使$monthnumber在此处变为"2"(或"02"),因为二月是第二个月。

只需使用date()函数。使用下方的代码

<?php
    $month_number = date('m', strtotime('1 February'));
    echo $month_number; //Prints 02

另一种方法是制作一个数组。使用下方的代码

 <?php
    $array = array("Januar"=>"01","Februar"=>"02","Mars"=>"03","April"=>"04","Mai"=>"05","Juni"=>"06","Juli"=>"07","August"=>"08","September"=>"09","Oktober"=>"10","November"=>"11","Desember");
    $month_name = "February";
    $month = ucwords(strtolower("Februar"));
    $month_number = $array[$month];
    echo $month_number; // Prints 02

希望这能帮助您

首先,您需要使用strtotime函数将月份转换为时间格式

strtotime函数的输出可以传递到日期函数,以数字格式生成月份

您可以使用以下代码

        $date = 'january';
        echo date('m', strtotime($date));

参考

,上述代码的输出将为01

像这样尝试

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