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:
//The "n" format character gives us //the month number without any leading zeros $month = date("n"); //Calculate the year quarter. $yearQuarter = ceil($month / 3); //Print it out echo "We are currently in Q$yearQuarter of " . date("Y");
In the example above:
- 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.
- To calculate the quarter, we divided the current month number by 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.
- 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:
//Our date. $dateStr = '2019-08-19'; //Get the month number of the date //in question. $month = date("n", strtotime($dateStr)); //Divide that month number by 3 and round up //using ceil. $yearQuarter = ceil($month / 3); //Print it out echo "The date $dateStr fell in Q$yearQuarter of " . date("Y", strtotime($dateStr));
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.