在PHP中解析本地化的日期字符串

时间:2011-01-11 07:46:12

标签: php localization

我有一些代码(它是wordpress插件的一部分),它接受一个文本字符串,并给出date()的格式说明符,并尝试将其解析为包含小时,分钟,秒,日,月的数组,年。

目前,我使用以下代码(请注意strtotime与01/02/03之类的东西非常不可靠)

// $format contains the string originally given to date(), and $content is the rendered string
if (function_exists('date_parse_from_format')) {
    $content_parsed = date_parse_from_format($format, $content);
} else {
    $content = preg_replace("([0-9]st|nd|rd|th)","\\1",$content);
    $content_parsed = strptime($content, dateFormatToStrftime($format));
    $content_parsed['hour']=$content_parsed['tm_hour'];
    $content_parsed['minute']=$content_parsed['tm_min'];
    $content_parsed['day']=$content_parsed['tm_mday'];
    $content_parsed['month']=$content_parsed['tm_mon'] + 1;
    $content_parsed['year']=$content_parsed['tm_year'] + 1900;
}

这实际上运作得相当好,似乎处理了我抛出的每一个组合。

然而,最近有人给了我24 Ноябрь, 2010。这是2010年11月24日的俄语[日期格式为j F, Y],它被解析为年份= 2010年,月份= null,日期= 24。

我是否可以使用哪些功能知道如何将11月和Ноябрь翻译成11?

编辑:

正在运行print_r(setlocale(LC_ALL, 0));会返回C。切换回strptime()似乎可以解决问题,但文档警告:

  

在内部,此函数调用系统C库提供的strptime()函数。此功能可以在不同的操作系统上表现出明显不同的行为。在PHP 5.3.0及更高版本中,建议使用不受这些问题影响的date_parse_from_format()。

date_parse_from_format()是否是正确的API,如果是,我该如何让它识别语言?

3 个答案:

答案 0 :(得分:3)

尝试将语言环境设置为俄语as hinted in the manual

  

月份和工作日名称以及其他语言相关字符串遵循使用setlocale() (LC_TIME设置的当前区域设置。

答案 1 :(得分:1)

你可以尝试使用locale参数并在进行日期解析之前调用locale_set_default($ locale)。

$originalLocale = locale_get_default();
$locale ? $locale : $originalLocale;
locale_set_default(locale);

// date parsing code

locale_set_default($originalLocale);

我没有对此进行测试,但尝试了一下。 仅供参考,我相信俄语的语言环境是“ru-Latn”

答案 2 :(得分:0)

我看到问题已经得到解答,但所提供的解决方案都没有对我有用。

这是我的解决方案:

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'])); 

}

其中t()返回月份的翻译缩写。

可能不是最好的解决方案(因为如果没有有效的翻译,它会失败)但它适用于我的情况。

相关问题