obokaman / dateranger
面向对象的日历管理
1.2.0
2020-07-30 14:48 UTC
Requires
- php: >=7.2
Requires (Dev)
- phpunit/phpunit: ^8.5
README
DateRanger 库提供了一个简单的方式来创建日期范围,允许扩展 DateRange
创建您自己的特殊范围,或者重用库中包含的基本范围(Year
、Month
、Week
或 Day
)。这个库受到了其他库的启发,比如 Calendr,由 Yohan Giarelli 开发,或者 Period,由 The PHP League 开发。
安装
DateRanger 在 Packagist 上可用,因此您可以使用 Composer 轻松安装。
只需运行以下命令
$ composer require obokaman/dateranger
或将库包含在项目的 composer.json 中
"require": { "php": ">=7.2", [...] "obokaman/dateranger": "^0.1", [...] },
示例
<?php include('vendor/autoload.php'); use DateRanger\Period\Year; $year = new Year(); echo "<h1>{$year->start()->format('Y')}</h1>"; foreach ($year as $month) { echo "<table><caption>{$month->start()->format('F')}</caption>"; echo "<thead><tr><th></th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th><th>Sun</th></tr></thead><tbody>"; foreach ($month as $week) { echo "<tr><td><small>{$week->start()->format('W')}</small></td>"; foreach ($week as $day) { if (!$day->overlaps($month)) $day_color = '#ddd;'; elseif ($day->isHoliday()) $day_color = 'red;'; else $day_color = '#333'; echo "<td style='border:1px solid #ccc;color:{$day_color}'>"; echo $day->start()->format('d') . '</td>'; } echo '</tr>'; } echo '</tbody></table>'; }
基本用法
库提供了几个从 DateRange
扩展的日期范围对象。所有这些对象都共享一些功能
start()
返回一个带有周期开始日期的 DateTimeImmutable 对象。end()
返回一个带有周期结束日期的 DateTimeImmutable 对象。getPeriod(string $interval)
返回一个基于当前 DateRange 的 DatePeriod 对象,根据给定的字符串格式间隔(与 DateInterval 构造函数接受的值相同)。overlaps(DateRange $period)
返回一个布尔值,表示周期是否与作为参数传递的其他 DateRange 发生重叠。isCurrent()
返回一个布尔值,表示周期是否是当前的:取决于所使用的类,当前年份、月份、星期或天。equals(DateRange $period)
比较当前周期和作为参数传递的周期之间的开始和结束日期。
如上所述,所有日期范围对象都从 DateRange
扩展,该对象实现了 Iterator
和 Countable
,因此可以直接使用 foreach
迭代它们的“子周期”,或使用 count
了解它们包含的数量。
例如
$year = Year::fromYear(2014); echo count($year); // returns 12.
$month = new Month('2014-01-01'); echo count($month) . PHP_EOL; // returns 5 (weeks). echo $month->start()->format('F') . PHP_EOL; // returns 'January'. foreach ($month as $week) { foreach ($week as $day) { if ($month->isOutOfMonth($day)) continue; echo $day->start()->format('Y-m-d') . PHP_EOL; // returns 2014-01-01\n [...] } }
贡献
欢迎评论、反馈和 PR!