sunkan / dictus
日期实用类
2.4.1
2024-05-28 08:28 UTC
Requires (Dev)
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^9.5
- stefna/codestyle: ^1.5
README
这是一个小型库,用于帮助进行日期格式化和在项目中保持一致的时钟
用法
使用格式化器
use Sunkan\Dictus\DateTimeFormat; use Sunkan\Dictus\DateTimeFormatter; use Sunkan\Dictus\LocalizedFormat; use Sunkan\Dictus\LocalizedStrftimeFormatter; use Sunkan\Dictus\LocalizedDateTimeFormatter; LocalizedDateTimeFormatter::addLocaleFormat('sv_SE', new \Sunkan\Dictus\Locales\SvSe()); $jsonDateFormatter = new DateTimeFormatter(DateTimeFormat::JSON); $localizedStrftimeFormatter = new LocalizedStrftimeFormatter('sv_SE', LocalizedFormat::DATETIME); $localizedDateTimeFormatter = new LocalizedDateTimeFormatter('sv_SE', 'l d F [kl.] H:i'); $date = new DateTimeImmutable(); echo $jsonDateFormatter->format($date); echo $localizedStrftimeFormatterFormatter->format($date); // 21.08.2023 16:26 echo $localizedDateTimeFormatter->format($date); // måndag 21 augusti kl. 16:26
使用本地化格式化器
我们建议使用 LocalizedDateTimeFormatter
,它仅支持翻译常规的 日期格式语法。
它将翻译以下键
D
日的简称l
日的全称M
月的简称F
月的全称
它还支持6个自定义键,有助于常见的本地化格式
冰岛语示例
'LT' => 'H:i', // 17:32 'LTS' => 'H:i:s', // 17:32:12 'L' => 'd.m.Y', // 06.12.2023 'LL' => 'j. F Y', // 6. desember 2023 'LLL' => 'j. F [kl.] H:i', // 6. desember kl. 17:32 'LLLL' => 'l j. F Y [kl.] H:i', // miðvikudagur 6. desember 2023 kl. 17:32
自定义本地化
要创建自己的本地化,只需创建一个实现 LocaleFormat
的类即可
final class CustomLocal implements \Sunkan\Dictus\LocaleFormat { public function formatChar(string $char, \DateTimeImmutable $dateTime): ?string { return match ($char) { 'D' => 'short custom weekday name', 'l' => 'long custom weekday name', 'M' => null, // use english month names 'F' => null, // use english month names default => null, }; } public function resolveFormat(string $format): ?string { return match($format) { 'LT' => 'H:i', // can be any valid date format string 'LTS' => 'H:i:s', // can be any valid date format string 'L' => 'd.m.Y', // can be any valid date format string 'LL' => 'j. F Y', // can be any valid date format string 'LLL' => 'j. F [kl.] H:i', // can be any valid date format string 'LLLL' => 'l j. F Y [kl.] H:i', // can be any valid date format string default => null, }; } }
时钟
该库提供了3种时钟实现
SystemClock, FrozenClock 和 ProjectClock
SystemClock
是围绕 new DateTimeImmutable('now')
的包装
FrozenClock
是围绕一个固定的 DateTimeImmutable
对象的包装
ProjectClock
是围绕一个 ClockInterface
实现的包装