로케일::getDefault()를 기준으로 DateTime 개체를 포맷합니다.
현재 형성 중인 DateTime 개체가 있습니다.
$mytime->format("D d.m.Y")
필요한 형식을 정확히 제공합니다.
2012년 3월 5일 화요일
유일하게 부족한 점은 올바른 언어입니다.의 독일어 번역이 필요합니다.Tue
(Tuesday
), 즉Die
(Dienstag
).
올바른 로케일 설정을 제공합니다.
Locale::getDefault()
하지만 어떻게 말해야 할지 모르겠어요DateTime::format
사용할 수 있습니다.
다음과 같은 작업을 수행할 수 있는 방법이 없을까요?
$mytime->format("D d.m.Y", \Locale::getDefault());
Intl 확장자를 사용하여 날짜 형식을 지정할 수 있습니다.선택한 로케일에 따라 날짜/시간 형식이 지정됩니다. 또는 로 재정의할 수 있습니다.
원하는 출력 형식에 사용자 지정 패턴을 사용하는 간단한 예는 다음과 같습니다.
$dt = new DateTime;
$formatter = new IntlDateFormatter('de_DE', IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
$formatter->setPattern('E d.M.yyyy');
echo $formatter->format($dt);
이는 다음을 출력합니다(최소한 오늘은).
Di. 4.6.2013
그것은format
로케일에 주의를 기울이지 않습니다.대신 사용해야 합니다.
예:
setlocale(LC_TIME, "de_DE"); //only necessary if the locale isn't already set
$formatted_time = strftime("%a %e.%l.%Y", $mytime->getTimestamp())
IntlDateFormatter는 현재(2023년) 가야 할 방법입니다.
<?php
$formatter = new IntlDateFormatter(
$locale, // the locale to use, e.g. 'en_GB'
$dateFormat, // how the date should be formatted, e.g. IntlDateFormatter::FULL
$timeFormat, // how the time should be formatted, e.g. IntlDateFormatter::FULL
'Europe/Berlin' // the time should be returned in which timezone?
);
echo $formatter->format(time());
전달한 내용에 따라 다른 출력을 제공합니다.$locale
날짜 및 시간 형식을 지정합니다.나중에 참고할 수 있도록 샘플을 추가하고 싶습니다.참고:IntlDateFormatter::GREGORIAN
그리고.IntlDateFormatter::LONG
교환이 가능합니다.
Locale: en_US
Format for Date & Time: Results in:
IntlDateFormatter::FULL Friday, August 5, 2022 at 3:26:37 PM Central European Summer Time
IntlDateFormatter::LONG August 5, 2022 at 3:26:37 PM GMT+2
IntlDateFormatter::MEDIUM Aug 5, 2022, 3:26:37 PM
IntlDateFormatter::SHORT 8/5/22, 3:26 PM
Locale: en_GB
Format for Date & Time: Results in:
IntlDateFormatter::FULL Friday, 5 August 2022 at 15:26:37 Central European Summer Time
IntlDateFormatter::LONG 5 August 2022 at 15:26:37 CEST
IntlDateFormatter::MEDIUM 5 Aug 2022, 15:26:37
IntlDateFormatter::SHORT 05/08/2022, 15:26
Locale: de_DE
Format for Date & Time: Results in:
IntlDateFormatter::FULL Freitag, 5. August 2022 um 15:26:37 Mitteleuropäische Sommerzeit
IntlDateFormatter::LONG 5. August 2022 um 15:26:37 MESZ
IntlDateFormatter::MEDIUM 05.08.2022, 15:26:37
IntlDateFormatter::SHORT 05.08.22, 15:26
Locale: fr_FR
Format for Date & Time: Results in:
IntlDateFormatter::FULL vendredi 5 août 2022 à 15:26:37 heure d’été d’Europe centrale
IntlDateFormatter::LONG 5 août 2022 à 15:26:37 UTC+2
IntlDateFormatter::MEDIUM 5 août 2022 à 15:26:37
IntlDateFormatter::SHORT 05/08/2022 15:26
Salatha가 이미 말했듯이, 필요한 경우 를 사용하여 출력을 추가로 사용자 지정할 수도 있습니다.
하는 동안에setlocale()
정답이고 계속 작동하지만 지금은 구식입니다.
Strftime은 PHP 8.1.0부터 사용되지 않습니다. 이 기능을 사용하는 것은 매우 권장되지 않습니다.
그리고 언급된 Intl 확장은 완벽하게 작동하지만 항상 유용한 것은 아닙니다.
날짜와 시간을 다루는 가장 간단한 방법 중 하나는 Carbon2, CakePHP Chronos 또는 유사한 라이브러리를 사용하는 것입니다.모든 날짜의 조작, 형식 지정 및 계산에 대한 단일 인터페이스를 제공합니다.만약 당신이 날짜 작업을 많이 한다면 카본을 사용한 후에 이런 것을 하는 것을 추천합니다.
$date = Carbon::now()->locale('fr_FR');
echo $date->isoFormat('dd DD.MM.YYYY');
형식이 다음과 다르다는 것을 참조하십시오.date()
1. 전체 목록은 탄소 문서에서 참조하지만 언급됨D d.m.Y
비슷한 것일 수 있습니다.dd DD.MM.YYYY
.
프로젝트에서 타사 라이브러리를 수락하는 것이 가장 좋은 방법입니다.또한 프레임워크를 사용하는 경우 Carbon(또는 포장지)이 이미 포함되어 있는지 확인하십시오.
온라인 어디에도 간단한 해결책이 존재하지 않는 것처럼 보이기 때문에 저는 그렇게 하는 것을 만들었습니다.strftime
그것은 매우 권장되지 않습니다!
내 솔루션은 확장됩니다.DateTime::format()
여러 모듈을 설치하거나 새로운 날짜 형식 지정 방법을 배우는 등의 작업을 수행할 필요가 없습니다.
아래에 제공되는 클래스를 포함한 후 다음과 같이 사용할 수 있습니다.대신에
$date = new DateTime("2010-01-01 1:23");
echo $date->format("l (D) Y-M-d (F)");
결과:Friday (Fri) 2010-Jan-01 (January)
이제 사용할 수 있습니다.
$date = new DateTimeIntl("2010-01-01 1:23");
echo $date->format("l (D) Y-M-d (F)");
결과:vrijdag (vr) 2010-jan.-01 (januari)
(네덜란드 로케일).
할 수 있습니다.$datetime->locale
$date = new DateTimeIntl("2010-01-01 1:23");
$date->locale = "it_IT" ;
echo $date->format("l (D) Y-M-d (F)");
결과:venerdì (ven) 2010-gen-01 (gennaio)
포함:
class DateTimePatternReplace {
function __construct(public string $DateTimeCode,
public string $IntDateFormatterCode,
public string $tempDateTimePlaceHolder) {}
}
trait addIntlDate {
public string $locale="nl_NL" ; // REPLACE BY YOUR FAVORITE LOCALE
private function getIntResult(string $pattern) {
if ( ! isset($this->formatter) || $this->formatter->getLocale(Locale::VALID_LOCALE) != $this->locale ) {
$this->formatter = new IntlDateFormatter($this->locale);
$this->locale = $this->formatter->getLocale(Locale::VALID_LOCALE); // store the valid version of the locale
}
this->formatter->setPattern($pattern);
return $this->formatter->format($this);
}
function format(string $pattern): string {
// The third parameter can NOT contain normal latin letters, these are random,
// distinctive codes not likely to be in a date format string
$replacePatterns = [/*weekdays*/new DateTimePatternReplace('l', 'EEEE', '[*ł*]'),
new DateTimePatternReplace('D', 'EEE', '[*Đ*]'),
/*month*/ new DateTimePatternReplace('F', 'MMMM', '[*ƒ*]'),
new DateTimePatternReplace('M', 'MMM', '[*μ*]'),
// add new replacements here if needed
] ;
$codesFound=[] ;
foreach($replacePatterns as $p) {
if ( str_contains($pattern, $p->DateTimeCode)) {
// replace codes not prepended by a backslash.
// known bug: codes prepended by double backslashes will not be translated. Whatever.
$pattern = preg_replace('/(?<!\\\)'.preg_quote($p->DateTimeCode)."/", $p->tempDateTimePlaceHolder, $pattern);
$codesFound[] = $p ;
}
}
$result = parent::format($pattern) ;
foreach($codesFound as $p) {
$code = $this->getIntResult($p->IntDateFormatterCode);
$result = str_replace($p->tempDateTimePlaceHolder, $code, $result);
}
return $result ;
}
}
// you can remove this str_contains addition in PHP 8 or higher
if (!function_exists('str_contains')) {
function str_contains($haystack, $needle) {
return $needle !== '' && mb_strpos($haystack, $needle) !== false;
}
}
// end str_contains addition
class DateTimeIntl extends DateTime {
use addIntlDate;
}
class DateTimeImmutableIntl extends DateTimeImmutable {
use addIntlDate;
}
이 코드는 DateTime 및 DateTimeImtable을 확장하고 로케일을 사용하여 일반 형식을 확장합니다.그래서 이것은 모든 것을 극도로 단순하게 유지합니다.
새할 수 . 즉 필한경 우요추 변패새추다있에 있는 포맷 입니다. 형식 지정 패턴은DateTime::format()
-filename, 의 해당 형식 지정 패턴IntlDateFormatter::format
place에서 , -splace에서 사용할 자리 표시자입니다.DateTime::format
"/" "/" "/" "/" "/" "/" "/" "/" "" "으로"이 되어 있지 .DateTime::format
하지 않는 의 코드 (, 예를 들어 128자 미만의 ASCII 문자를 사용하지 않는 현재 4개의 코드를 참조하십시오. (폴란드어, 그리스어, 네덜란드어, 슬로바키아어 문자는 재미로 사용합니다.)
PHP 8.1에서 구축 및 테스트되었습니다.일부 오래된 버전의 PHP의 경우 첫 번째 클래스를 다음으로 변경해야 합니다.
class DateTimePatternReplace {
public string $DateTimeCode;
public string $IntDateFormatterCode;
public string $tempDateTimePlaceHolder;
function __construct(string $DateTimeCode, string $IntDateFormatterCode, string $tempDateTimePlaceHolder) {
$this->DateTimeCode = $DateTimeCode;
$this->IntDateFormatterCode = $IntDateFormatterCode;
$this->tempDateTimePlaceHolder = $tempDateTimePlaceHolder;
}
}
DateTime()과 strfttime()의 기능을 결합하여 이렇게 해결했습니다.
첫 번째는 "Ymd"(날짜 선택기에서 db에 저장)와 같은 이상한 날짜 형식의 문자열을 관리할 수 있게 해줍니다.두 번째는 날짜 문자열을 어떤 언어로 번역할 수 있게 해줍니다.
예를 들어, "20201129" 값으로 시작하고 이탈리아어로 읽을 수 있는 날짜로 끝나려면 날짜와 월 이름, 첫 번째 문자 대문자: "Domenica 29 novembre 2020"으로 끝나야 합니다.
// for example we start from a variable like this
$yyyymmdd = '20201129';
// set the local time to italian
date_default_timezone_set('Europe/Rome');
setlocale(LC_ALL, 'it_IT.utf8');
// convert the variable $yyyymmdd to a real date with DateTime
$truedate = DateTime::createFromFormat('Ymd', $yyyymmdd);
// check if the result is a date (true) else do nothing
if($truedate){
// output the date using strftime
// note the value passed using format->('U'), it is a conversion to timestamp
echo ucfirst(strftime('%A %d %B %Y', $truedate->format('U')));
}
// final result: Domenica 29 novembre 2020
언급URL : https://stackoverflow.com/questions/8744952/formatting-datetime-object-respecting-localegetdefault
'it-source' 카테고리의 다른 글
Oracle SQL: 테이블 이름 대신 사용되는 변수 (0) | 2023.08.14 |
---|---|
Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - 각 항목을 언제 사용해야 합니까? (0) | 2023.08.14 |
Action Creator 및 Reducer 없이 React 및 Redux에서 AJAX 호출을 보낼 수 있습니까? (0) | 2023.08.14 |
SQL 서버 테이블에 대량의 텍스트를 저장하는 가장 좋은 방법은 무엇입니까? (0) | 2023.08.14 |
xcrun: 오류: 개발자 도구나 PATH가 아닌 유틸리티 "xctest"를 찾을 수 없습니다. (0) | 2023.08.14 |