2011-01-11 7 views
5

텍스트 문자열과 date()에 주어진 형식 지정자를 사용하고 시간, 분, 초를 포함하는 배열로 구문 분석하려는 일부 코드 (WordPress 플러그인의 일부) 두 번째, 일, 월, 일.PHP에서 현지화 된 날짜 문자열 구문 분석

현재, 나는이 실제로 꽤 잘 작동

// $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; 
} 

, 내가 던진 한 모든 조합을 처리하는 것 (즉, strtotime으로는 01/02/03 같은 것들에 끔찍하게 신뢰할 주) 다음 코드를 사용하여 그것.

그러나 최근에는 누군가가 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

봅니다 러시아 as hinted in the manual에 로케일을 설정하려면 다음

월과 요일 이름과 기타 언어 의존 문자열은 setlocale()(LC_TIME로 설정된 현재의 로케일을) 존중합니다.

+0

문제는 다른 사람들이 사용할 수있는 플러그인이라는 것입니다. "적절한"해결책을 찾는 것이 좋을 것입니다. 하지만 작동하지 않을 때까지'strptime() '을 고수 할 것입니다. – Mikeage

+0

@Mikeage UnitTest가 적절하다.'date_create_from_format'가 지역화 된 문자열을 구문 분석 할 수 있다면 시도해 볼 수 있습니다. 나는 그것이 생각하지 않는다. 그러나 그것을 그럼에도 불구하고 시험해 보라. – Gordon

+0

저는 18 Mag 2013 (= 2013-05-18)과 같이 이탈리아 날짜를 구문 분석하기 위해 strptime()과 date_create_from_format를 모두 시도했지만 성공하지 못했습니다. – damko

1

로캘 매개 변수를 가져 와서 날짜 구문 분석을 수행하기 전에 locale_set_default ($ locale)를 호출 해 볼 수 있습니다.

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

// date parsing code 

locale_set_default($originalLocale); 

나는 이것을 테스트하지는 않았다. 참고로 러시아어의 로켈 문자열은 "ru-Latn"이라고 생각합니다.

+0

제 문제는 로케일이 무엇이되어야할지 모르며, 이미 설정되어 있다고 가정합니다. – Mikeage

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

} 

톤은() 월의 번역 약어를 반환

이 내 솔루션입니다.

아마도 유효한 솔루션이 아닐 것입니다. (유효한 번역이 없으면 실패 할 수 있기 때문에) 내 경우에는 효과가 있습니다.