Kristian Rafteseth
Kristian Rafteseth

Reputation: 2032

PHP: Convert local monthname to monthnumber

How would one go about converting a local name of the month, to the respective month number?

You could just make the translation manually, but I'm pretty sure PHP got some built in functions for this?

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

The goal is for $monthnumber to become '2' here (or '02'), since february is the second month.

Upvotes: 0

Views: 104

Answers (3)

Utkarsh Dixit
Utkarsh Dixit

Reputation: 4275

Just use the date() function. Use the code below

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

Another way you can do it by making an array. Use the code below

 <?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

Hope this helps you

Upvotes: 1

Priyank
Priyank

Reputation: 3868

try like this

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

Upvotes: 0

Pavan Jiwnani
Pavan Jiwnani

Reputation: 274

First of all you need to convert the month to time format using strtotime function

The output of strtotime function can be passed to date function to generate the month in numerical format

you can use the following code

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

The output of the above code will be 01 refering to

Upvotes: 0

Related Questions