Parsing localized date strings in PHP

后端 未结 3 1916
灰色年华
灰色年华 2020-12-11 05:53

I have some code (it\'s part of a wordpress plugin) which takes a text string, and the format specifier given to date(), and attempts to parse it into an array containing ho

相关标签:
3条回答
  • 2020-12-11 06:38

    Try to set the locale to Russian as hinted in the manual:

    Month and weekday names and other language dependent strings respect the current locale set with setlocale() (LC_TIME).

    0 讨论(0)
  • 2020-12-11 06:40

    I see that the question is already answered but none of the solutions provided worked for me.

    This is my solution:

    if(!preg_match('/^en_US/', $locale)){
    
        $months_short = array('jan' => t('jan'), 'feb' => t('feb'), 'mar' => t('mar'), 'apr' => t('apr'),
                'may' => t('may'), 'jun' => t('giu'), 'jul' => t('lug'), 'aug' => t('ago'),
                'sep' => t('set'), 'oct' => t('ott'), 'nov' => t('nov'), 'dec' => t('dec'));
    
        foreach ($months_short as $month_short => $month_short_translated) {
            $date = preg_replace('/'.$month_short_translated.'/', $month_short, strtolower($date));
        }
    
    }
    
    $pieces = date_parse_from_format($format,$date);
    
    if($pieces && $pieces['error_count'] == 0 && checkdate($pieces['month'], $pieces['day'], $pieces['year'])){
    
        return date('Y-m-d', mktime(0,0,0,$pieces['month'],$pieces['day'],$pieces['year'])); 
    
    }
    

    Where t() returns the translated abbreviation for the month.

    Probably not the best solution ever (because it fails if there is no valid translation) but it works for my case.

    0 讨论(0)
  • 2020-12-11 06:46

    you could try take a locale parameter and call locale_set_default($locale) before doing the date parsing.

    $originalLocale = locale_get_default();
    $locale ? $locale : $originalLocale;
    locale_set_default(locale);
    
    // date parsing code
    
    locale_set_default($originalLocale);
    

    I haven't testing this but it's work a try. FYI, I believe the locale string for Russian is "ru-Latn"

    0 讨论(0)
提交回复
热议问题