Calculating Dates in PHP

Displaying dates in PHP is a no brainer. You simply echo the date() function to display the current date. For example, echo date(‘Y-m-d’) will display the current date in the ISO date format of ‘2012-02-27.’ However, calculating dates in the past or in the future is a tiny bit more tricky. For accuracy, I recommend that you use mktime(), which converts time to Unix timestamp. You can then perform date calculations in Unix timestamp which is much more accurate. You do have the option to change the format back to ISO, if you desire. Here are a few examples.

Display the current date:

echo date('Y-m-d');

Output: 2012-02-27

Convert to mktime:

$t = mktime(0, 0, 0, date("m"), date("j"), date("Y"))

Display the start of the current month:

echo date('Y-m-d', mktime(0, 0, 0, date("m"), 1, date("Y")));

Output: 2012-02-01

Display the end of the current month:

echo date('Y-m-d', mktime(23, 59, 59, date("m")+1, 0, date("Y")));

Output: 2012-02-29

Display the start of last month:

echo date('Y-m-d', mktime(0, 0, 0, date("m")-1, 1, date("Y")));

Output: 2012-01-01

To display the end of last month:

echo date('Y-m-d', mktime(23, 59, 59, date("m"), 0, date("Y")));

Output: 2012-01-31

Display the start of next month:

echo date('Y-m-d', mktime(0, 0, 0, date("m")+1, 1, date("Y")));

Output: 2012-03-01

Display the end of next month:

echo date('Y-m-d', mktime(0, 0, 0, date("m")+2, 0, date("Y")));

Output: 2012-03-31

This code is very flexible. If you like to display the dates to any other format, you can change the date format to any format that you like. Check out all the different date formats. I hope this was helpful.