PHP: Get the year quarter from a date.

This is a tutorial on how to get the year quarter of a date using PHP. In this guide, I will show you how to determine the current quarter, as well as how to get the quarter of a given date.

Getting the current quarter.

In this example, we get the quarter of the current calendar year:

In the example above:

  1. We used PHP’s date function to get the numeric representation of the current month. We used the “n” format character because it will return a number between 1-12 without any leading zeros.
  2. To calculate the quarter, we divided the current month number by 3.
  3. We then used the ceil function to round the number up to the next highest integer value. If you fail to round this figure up, months such as January will result in 0 and decimal places.
  4. Finally, we printed out the current quarter. In the example above, I used “Q” because the quarters in a calendar year are typically abbreviated as Q1, Q2, Q3 or Q4.

Getting the quarter of a given date.

If you want to determine which quarter a given date falls into, then you can use the following example:

In the PHP code above, I calculated which quarter the date “2019-08-19” falls into. If you run this example in your browser, you will see that the output is:

The date 2019-08-19 fell in Q3 of 2019

This is correct, as the month of August falls into the third quarter of each year.

Note that in this case, we passed in the UNIX timestamp of “2019-08-19” as a second parameter to PHP’s date function.

Facebook Comments