Calculating Start and End Timestamps for Current and Previous Months in PHP
To compute the timestamps for the first and last days of the current and previous months in PHP, developers commonly use built-in date and time functions such as mktime(), strtotime(), and date(). Below are practical and reliable approaches to achieve this.
Using mktime() for Month Boundaries
The mktime() function constructs a Unix timestamp from a date. For the current month:
$startOfCurrentMonth = mktime(0, 0, 0, date('n'), 1, date('Y'));
$endOfCurrentMonth = mktime(23, 59, 59, date('n'), date('t'), date('Y'));
For the previosu month:
$startOfLastMonth = mktime(0, 0, 0, date('n') - 1, 1, date('Y'));
$endOfLastMonth = mktime(23, 59, 59, date('n'), 0, date('Y'));
Note: Passing 0 as the day in mktime() automatically resolves to the last day of the previous month.
Alternative with strtotime()
A more readable approach uses relative date strings with strtotime():
$currentYear = date('Y');
$currentMonth = date('m');
// Current month
$monthStart = strtotime("$currentYear-$currentMonth-01 00:00:00");
$monthEnd = strtotime("$currentYear-$currentMonth-" . date('t') . " 23:59:59");
// Previous month
$lastMonthStart = strtotime('first day of last month 00:00:00');
$lastMonthEnd = strtotime('last day of last month 23:59:59');
This method leverages PHP’s natural language date parser, which is less error-prone when handling month transitions (e.g., January to December of the prior year).
Formatting for Database Queries
Once timestamps are obtained, they can be formatted for SQL queries:
$startDate = date('Y-m-d', $startOfLastMonth);
$endDate = date('Y-m-d', $endOfLastMonth);
$whereClause = "BETWEEN '$startDate' AND '$endDate'";
This ensures clean integration with database systems that expect date strings in YYYY-MM-DD format.