In this tutorial, we walk through a few different scenarios of using league/period. The package league/period is from PHP League and its purpose is to make handling date range in PHP easier for developers.
First thing first, let's install the league/period using composer as normal:
composer require league/period
If you have a $startDate and $endDate, how can you check if a date given by the user falls within that range?
For example, if we have dates as shown below
$startDate = '2009-06-17';
$endDate = '2009-09-05';
$dateFromUser = '2009-08-28';
We can use the method contains() of Period class to accomplish that:
Given a date range between $startDate and $endDate, how can you get all dates between these two dates in an array?
For example, if we have dates as shown below:
$startDate = '2009-06-17';
$endDate = '2009-09-05';
We can use the method getDatePeriod() of Period class to accomplish that:
$startDate = '2009-06-17';
$endDate = '2009-06-25';
$period = new Period($startDate, $endDate);
foreach ($period->getDatePeriod('1 DAY') as $day) {
var_dump($day->format('Y-m-d'));
}
// Output
//string(10) "2009-06-17"
//string(10) "2009-06-18"
//string(10) "2009-06-19"
//string(10) "2009-06-20"
//string(10) "2009-06-21"
//string(10) "2009-06-22"
//string(10) "2009-06-23"
//string(10) "2009-06-24"
Given a date range between $startDate and $endDate:
$startDate = '2009-06-17';
$endDate = '2009-09-05';
How can you verify if the dates below are in the range of the date range above?
$myStartDate = '2009-07-17';
$myEndDate = '2009-08-05';
We can use the method contains() of Period class to accomplish that:
$startDate = '2009-06-17';
$endDate = '2009-09-05';
$myStartDate = '2009-07-17';
$myEndDate = '2009-08-05';
$periodOne = new Period($startDate, $endDate);
$periodTwo = new Period($myStartDate, $myEndDate);
var_dump($periodOne->contains($periodTwo));
// Output
// bool(true)
Suppose you accept two user inputs $startDate and $endDate from a form. How do you valid if these two dates can form a valid date range. Normal Dates comparison would work, but it requires you to write your custom objects to handle that validation elegantly.
We can use Period class since it already handles those validations for us. It will make sure it is a valid date range upon instantiation of a Period instance.
$startDate = '2009-06-17';
$endDate = '2009-09-05';
$period = new Period($endDate, $startDate);
// Output
// Fatal error: Uncaught exception 'LogicException' with message 'The ending datepoint must be greater or equal to the starting datepoint'
Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.