buffalokiwi / buffalotools_date
PHP 7.4 的简单日期包装器
v1.0.5
2021-07-26 10:14 UTC
Requires
- php: ^7.4 || ^8.0
Requires (Dev)
- phpunit/phpunit: ^9.3
README
此软件包包含一个简单的日期工厂,用于将各种格式的日期转换为 DateTimeInterface 实例,以及一个用于在单个对象中存储 UTC 和本地时间的 DateTime 包装器。
MIT 许可证
安装
composer require buffalokiwi/buffalotools_date
概述
DateFactory 用于创建 DateTimeInterface 和 IDateTime 的实例。想法是传递本地时区和一些应用中可能遇到的日期格式字符串列表。使用提供的格式(或支持 \DateTime 的格式)中的任何一种日期字符串调用 createDateTime() 将返回有效的 DateTimeImmutable 对象或抛出异常。
DateTimeWrapper 用于包装 DateTimeInterface 的实例,并为给定 DateTimeInterface 对象提供对 UTC 和本地时间的轻松访问。
示例
$factory = new buffalokiwi\buffalotools\date\DateFactory( 'America/New_York' ); //..createDateTime returns whatever date you pass with the timezone set to whatever zone is supplied. //..Defaults to UTC. No time zone conversions occurs within this method. $utc = $factory->createDateTime( '2021-01-01 12:00:00' ); print_r( $utc ); /* DateTimeImmutable Object ( [date] => 2021-01-01 12:00:00.000000 [timezone_type] => 3 [timezone] => UTC ) */ //..Create a date time but set the time zone to new york. $local = $factory->createDateTime( '2021-01-01 12:00:00', 'America/New_York' ); print_r( $local ); /* DateTimeImmutable Object ( [date] => 2021-01-01 12:00:00.000000 [timezone_type] => 3 [timezone] => America/New_York ) */ //..createIDateTime is the same as createDateTime, except it always returns the date in UTC. // If a non-UTC timezone is passed, the date is converted to UTC. // createIDateTime returns instances of IDateTime //..Create a date time in UTC $utc = $factory->createIDateTime( '2021-01-01 12:00:00' ); print_r( $utc->getUTC()); /* DateTimeImmutable Object ( [date] => 2021-01-01 12:00:00.000000 [timezone_type] => 3 [timezone] => UTC ) */ print_r( $utc->getLocal()); /* DateTimeImmutable Object ( [date] => 2021-01-01 07:00:00.000000 [timezone_type] => 3 [timezone] => America/New_York ) */ //..Create a local date time. UTC will be a few hours in the future. //..Using this method will set getLocal() to the supplied datetime. $local = $factory->createIDateTime( '2021-01-01 12:00:00', 'America/New_York' ); print_r( $local->getUTC()); /* DateTimeImmutable Object ( [date] => 2021-01-01 17:00:00.000000 [timezone_type] => 3 [timezone] => UTC ) */ print_r( $local->getLocal()); /* DateTimeImmutable Object ( [date] => 2021-01-01 12:00:00.000000 [timezone_type] => 3 [timezone] => America/New_York ) */
DateFactory 有一个 now() 方法,可以用来返回 UTC 或相对于 UTC 的当前日期时间。
//..Retrieve "now" in UTC print_r( $factory->now()); /* DateTimeImmutable Object ( [date] => 2021-04-25 16:22:07.073529 [timezone_type] => 3 [timezone] => UTC ) */ //..Retrieve "now" in some time zone relative to UTC. //..Converts UTC to the supplied time zone print_r( $factory->now( 'America/New_York' )); /* DateTimeImmutable Object ( [date] => 2021-04-25 12:22:07.073529 [timezone_type] => 3 [timezone] => America/New_York ) */