Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Calculating Start and End Timestamps for Current and Previous Months in PHP

Tech May 31 1

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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.