get next and previous day with PHP
When building interfaces that display dates, such as a calendar or a timeline view, you often need to programmatically calculate adjacent days. The source material presents a common scenario where a developer wants to add navigation links for "previous day" and "next day," but encounters a limitation where clicking the next button only advances time by one day instead of continuing forward. This behavior stems from how PHP's date() and strtotime() functions handle string manipulation versus stateful iteration.
The provided code snippet demonstrates the standard approach to generating relative dates:
<?php
// Previous day link
$prevDate = date('Y-m-d', strtotime('-1 day', strtotime($date)));
echo '<a href="home.php?date=' . $prevDate . '" class="prev_day" title="Previous Day"></a>';
// Next day link
$nextDate = date('Y-m-d', strtotime('+1 day', strtotime($date)));
echo '<a href="home.php?date=' . $nextDate . '" class="next_day" title="Next Day"></a>';
?>
This logic is sound for rendering a static HTML page. When the user clicks the "Next Day" link, the server receives the new date in the query string (e.g., home.php?date=2023-10-26). The server then executes the PHP script again, re-calculating the links based on that fresh date. Consequently, every time you click "Next," the starting point shifts by one day, naturally creating a continuous progression without needing complex state management.
The confusion often arises when developers expect client-side JavaScript to handle the counting or when they try to increment a variable directly within the PHP output logic without passing the updated state back to the server. In a standard web request/response cycle, PHP is executed once per page load. If you want the links to behave like an infinite scroll where the "Next" button always points to the immediate future relative to the current displayed date, you must ensure the variable $date passed to the view reflects the most recent server-side calculation.
If your application uses a framework like Laravel, the logic remains identical regarding the core PHP functions, but the syntax for accessing variables changes. Assuming you are passing a formatted date string from your controller or model to your Blade template, you can apply the same strtotime offset:
// In a Blade view
$today = $request->input('date', date('Y-m-d')); // Default to today if not provided
$prevDay = date('Y-m-d', strtotime('-1 day', $today));
$nextDay = date('Y-m-d', strtotime('+1 day', $today));
// Generate links
<a href="/home?date={$prevDay}" class="btn-prev">Previous Day</a>
<a href="/home?date={$nextDay}" class="btn-next">Next Day</a>
The critical detail here is that strtotime() accepts a relative string (like '+1 day') and an absolute timestamp or date string. When you nest them as strtotime('+1 day', strtotime($date)), the second argument ensures the calculation starts from the specific $date variable rather than the current server time (now). This is vital if your application needs to display historical dates or future projections that are not tied to the moment the page is rendered.
A common pitfall in this architecture is forgetting to sanitize or validate the incoming date parameter from the query string. If a user manually alters the URL to home.php?date=invalid-date, strtotime() might return a Unix timestamp of 0 (January 1, 1970), causing your links to jump to that date instead of relative ones. Always default to a safe baseline if the input is invalid:
$rawDate = $request->input('date', '');
$safeDate = $rawDate ?: date('Y-m-d'); // Fallback to today
By ensuring the base date is always valid, your navigation links will consistently calculate the correct adjacent days. The continuous change you are looking for happens automatically because each request resolves to a new state based on the URL parameter. There is no need to "remember" the count of clicks; the server re-evaluates the "next" logic every time the page loads with a new date context.