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.

Table Of Content

  1. Installing package
  2. Checking if a date falls in between a date range
  3. Checking if a date falls in between a date range
  4. Checking if a date range falls in between another date range
  5. Checking if two dates can form a valid date range
  6. The end
1. Installing package

First thing first, let's install the league/period using composer as normal:

2. Checking if a date falls in between a date range

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:

We can use the method contains() of Period class to accomplish that:

3. Returning all dates between two dates in an array

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:

We can use the method getDatePeriod() of Period class to accomplish that:

4. Checking if a date range falls in between another date range

Given a date range between $startDate and $endDate:

How can you verify if the dates below are in the range of the date range above?

We can use the method contains() of Period class to accomplish that:

5. Checking if two dates can form a valid date range

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.

6. The end

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.