简体   繁体   中英

Convert Month Name into Number With Different Languages?

I want to convert Month Name into Number format with different Languages. I have written one code that code is working on my localhost but its not working on live server its returning false value. And also for some months its working and its not working for Dezembro , outubro its not working. How i can solve this issue ? Could you please help me to solve this one ??

$visit_date = "7 Dezembro, 2019";

 $split_date = explode(" ", $visit_date);  
      $visit_day = sprintf("%02d", $split_date[0]);
      $visit_month = $split_date[1];     

          if (substr($visit_month, -1) == ',')
          {
              $visit_month = substr($visit_month, 0, -1);
              $visit_year =   $split_date[2];   

          }      
          else {
              $visit_year =   $split_date[3];     
          }      

          var_dump($visit_month);
      $visit_month =  month_to_number($visit_month, 'pt_PT');

var_dump($visit_month);



// convert visit date month full name to month number for all languages
function month_to_number($month, $locale_set= 'pt_PT' )
{

    $month  = mb_convert_case($month, MB_CASE_LOWER, 'UTF-8');

    $locale =
        setlocale(LC_TIME, '0');
        setlocale(LC_TIME, $locale_set.'.UTF-8');

    $month_number = FALSE;

    for ($i = 1; $i <= 12; $i++)
    {
        $time_month     = mktime(0, 0, 0, $i, 1, 1970);
        $short_month    = date('M', $time_month);
        $short_month_lc = strftime('%b', $time_month);

        if (stripos($month, $short_month) === 0 OR
            stripos($month, $short_month_lc) === 0)
        {
            $month_number = sprintf("%02d", $i);

            break;
        }
    }

    setlocale(LC_TIME, $locale); // return locale back

    return $month_number;

}

If you can integrate the external class dt try this:

$visit_date = "7 Dezembro, 2019";

dt::setDefaultLanguage('pt');
$dt = dt::create($visit_date);

echo $dt->format('Y-m-d');//2019-12-07

Internally, the class creates a translation table for every month when setting the language. The IntlDateFormatter class is used for this.

Note: The IntlDateFormatter class works independently of the server's local settings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM