dasprid / local-date-time
本地日期和时间实现
Requires
- php: ~7.2
Requires (Dev)
- ext-intl: ^1.1
- doctrine/dbal: ^2.9
- phpunit/phpunit: ^8.0
- squizlabs/php_codesniffer: ^3.4
Suggests
- ext-intl: For using the IntlLocalDateFormatter
- doctrine/dbal: For using the Doctrine types
This package is auto-updated.
Last update: 2022-04-10 21:54:43 UTC
README
LocalDateTime 是 PHP 自己的 DateTime 对象的轻量级包装,允许在无需担心时区的情况下轻松处理本地日期、时间和日期时间。每个时间对象都允许与底层 DateTime 对象相同的方式进行比较、修改和格式化。
此外,此库还提供了一个IntlDateFormatter的包装,专门用于格式化本地时间。为了便于集成,还提供了这些时间对象的Doctrine类型。
安装
通过composer安装
$ composer require dasprid/local-date-time
入门指南
提供了三个时间对象
DASPRiD\LocalDateTime\LocalDate
DASPRiD\LocalDateTime\LocalTime
DASPRiD\LocalDateTime\LocalDateTime
所有这些都可以通过命名构造函数以类似的方式构造。为了简单起见,以下示例展示了如何使用 LocalDate
对象。
创建
LocalDate
对象可以通过多种方式创建
<?php use DASPRiD\LocalDateTime\LocalDate; $date = LocalDate::createFromNow(); $date = LocalDate::create(2019, 12, 31); $date = LocalDate::createFromFormat('Y-m-d', '2019-12-31'); $date = LocalDate::createFromDateTime(new DateTime('2019-12-31'));
当从 DateTime
对象创建 LocalDate
时,它将按照 DateTime
对象设置的时区进行解释。如果您希望在不同时区中解释它,您必须在 DateTime
对象之前更改它。
修改
如前所述,LocalDate
支持与常规 DateTime
对象相同的修改方法
::modify(string $modify) : self
::add(DateInterval $interval) : self
::sub(DateInterval $interval) : self
当修改包含不属于时间(例如 LocalDate
的小时)的单位时,它将应用于底层 DateTime
对象,之后将其删除。例如
<?php use DASPRiD\LocalDateTime\LocalDate; $date = LocalDate::create(2019, 12, 31); $newDate = $date->modify('-1 hour'); // $newDate will now be 2019-12-30, with the internal DateTime time reset to 00:00:00
比较
比较与 DateTime
对象相同,除了PHP代码无法覆盖比较器,以下方法被提供
::compare(self $other) : int
::isBefore(self $other) : bool
::isAfter(self $other) : bool
::isEqual(self $other) : bool
::diff(self $other, bool $absolute = false) : DateInterval
格式化
格式化与您所习惯的方式相同。根据时间对象,某些特定的格式化字符可能不支持,并将按原样返回。例如,没有本地时间支持时区信息,并且 LocalDate
无法返回任何时间信息。
<?php use DASPRiD\LocalDateTime\LocalDate; $date = LocalDate::create(2019, 12, 31); echo $date->format('d.m.Y'); // Outputs: 31.12.2019
要格式化特定于特定区域的语言的日期(而不是英语),您将需要使用 IntlLocalDateFormatter
,这需要安装 ext-intl
。要格式化上述日期为德语区域,您将执行以下操作
<?php use DASPRiD\LocalDateTime\LocalDate; use DASPRiD\LocalDateTime\IntlLocalDateFormatter; $date = LocalDate::create(2019, 12, 31); $formatter = IntlLocalDateFormatter::dateFormatter('de-DE', IntlDateFormatter::FULL); echo $formatter->format($date);
Doctrine集成
在使用Doctrine时,以下Doctrine类型可用于本地时间
DASPRiD\LocalDateTime\Doctrine\LocalDateType
(名称:localdate
)DASPRiD\LocalDateTime\Doctrine\LocalTimeType
(名称:localtime
)DASPRiD\LocalDateTime\Doctrine\LocalDateTimeType
(名称:localdatetime
)