Search code examples
phpdatesetlocale

Get month number from name from other language


If I have a month name in a certain language(let's say Albanian), how do I get the number corresponding to it (in PHP)? Besides the obvious method of making an array with the month names of that language (I'm afraid that's quite vulnerable to spelling mistakes) I presume that you can use setlocale but I can't figure out what to do next.


Solution

  • I may be wrong but, as far as I know, you can use locales to generate month names but there aren't builtin date functions that are able to parse non-English names.

    It should be fairly easy to generate a list of names to compare against:

    <?php
    
    $langs = array(
        // Windows only locale names
        'Albanian',
        'French',
        'German',
        'Spanish',
    );
    $months = array();
    
    foreach($langs as $lang){
        setlocale(LC_TIME, $lang);
        foreach(range(1, 12) as $i){
            $months[$lang][$i] = strftime('%B', mktime(0, 0, 0, $i));
        }
    }
    

    However, it's possible that there're alternative spellings in some languages so the reliability of this method actually depends on your exact needs.

    PHP has some Internationalization Functions that might be a better bet. The IntlDateFormatter::parse() method appears to do exactly what you are asking. However, its requirements include PHP 5 >= 5.3.0, PECL intl >= 1.0.0.