我制作了一个东西来实现这个功能,因为似乎在网上除了
strftime
(已经非常过时)之外没有简单的解决方案!我的解决方案通过国际化月份和日期名称扩展了
DateTime::format()
,不需要安装一堆模块、学习新的日期格式等等。在包含下面提供的类之后,您可以按照以下方式使用它。而不是:
$date = new DateTime("2010-01-01 1:23");
echo $date->format("l (D) Y-M-d (F)");
结果: 星期五 (周五) 2010年1月1日 (一月)
现在您可以使用
$date = new DateTimeIntl("2010-01-01 1:23");
echo $date->format("l (D) Y-M-d (F)");
结果: 2010年1月1日星期五(荷兰语环境)
.
如果需要,您可以动态更改$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" ;
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);
}
this->formatter->setPattern($pattern);
return $this->formatter->format($this);
}
function format(string $pattern): string {
$replacePatterns = [new DateTimePatternReplace('l', 'EEEE', '[*ł*]'),
new DateTimePatternReplace('D', 'EEE', '[*Đ*]'),
new DateTimePatternReplace('F', 'MMMM', '[*ƒ*]'),
new DateTimePatternReplace('M', 'MMM', '[*μ*]'),
] ;
$codesFound=[] ;
foreach($replacePatterns as $p) {
if ( str_contains($pattern, $p->DateTimeCode)) {
$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 ;
}
}
if (!function_exists('str_contains')) {
function str_contains($haystack, $needle) {
return $needle !== '' && mb_strpos($haystack, $needle) !== false;
}
}
class DateTimeIntl extends DateTime {
use addIntlDate;
}
class DateTimeImmutableIntl extends DateTimeImmutable {
use addIntlDate;
}
这段代码扩展了DateTime和DateTimeImmutable,通过区域设置扩展了它们的普通格式。因此,这使一切变得非常简单。
如果需要,您可以通过将代码添加到数组中来添加要翻译的新模式:在DateTime::format()
语法中的格式化模式,对应的IntlDateFormatter::format
语法中的格式化模式,以及一个占位符,用于DateTime::format
,该占位符不包含将由DateTime::format
方法使用/替换的字母/代码/模式。例如,查看当前使用ASCII小于128个字母的四个代码示例(它们仅出于乐趣使用波兰语、希腊语、荷兰语和斯洛伐克语字母)。
在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;
}
}