Imagine you’re working on a PHP project and trying to get the Previous date to calculate data. you can get the previous date by using the DateTime
class or with the strtotime
function.
Here are two common methods:
How to get yesterday and tomorrow dates in PHP
Method 1: DateTime
class in PHP
Using the DateTime
class in PHP is a powerful and flexible way to handle dates and times
$date = new DateTime(); // Create a new DateTime object for the current date and time
$date->modify('-1 day'); // Subtract one day
$previousDate = $date->format('Y-m-d'); // Format the date as YYYY-MM-DD
echo $previousDate;
Output:
Get Tomorrow/Next date in php
To get tomorrow's date in PHP simply change the modify
method to add one day. like below
$date = new DateTime(); // Create a new DateTime object for the current date and time
$date->modify('+1 day'); // Subtract one day
$previousDate = $date->format('Y-m-d'); // Format the date as YYYY-MM-DD
echo $previousDate;
Using a Specific Date:
If you want to get the Previous or tomorrow's date from a specific date, you need to change the DateTime(); method.
$date = new DateTime('2024-10-10'); // Example specific date
$date->modify('+1 day'); // Subtract one day
$previousDate = $date->format('Y-m-d'); // Format the date as YYYY-MM-DD
echo $previousDate;
Method 2: Using strtotime
You can also get tomorrow's date in PHP using the strtotime
function. Here's how to do it:
$opening_date = '2024-10-10';
$closing_date = date('Y-m-d', strtotime('-1 day', strtotime($opening_date))); // Add one day to the current date
echo $closing_date ; // Output tomorrow's date
Output:
You will get the 2024-10-09 date in output.
Using strtotime
is a simple and effective way to manipulate dates in PHP, especially for relative date calculations.
If you have any other questions or need further examples, let us know and upload the question in our forum tapgen.xyz
Learn to code with the world's largest web developer site. Not sure where to begin? HTML is The language for building web pages Learn HTML Tutorial with Tapgen.
=================================