PHP Date Exercises : Get yesterday's date
13. Get Yesterday's Date
Write a PHP script to get yesterday's date.
Sample Solution:
PHP Code:
<?php
$dt = new DateTime(); // Creating a new DateTime object representing the current date and time.
$dt->sub(new DateInterval('P1D')); // Subtracting one day from the DateTime object using the sub() method and a DateInterval of one day.
echo $dt->format('F j, Y')."\n"; // Formatting the modified date and time as "Month Day, Year" and outputting it, followed by a newline character.
?>
Output:
July 10, 2017
N.B.: The result may varry for your system date and time.
Explanation:
In the exercise above,
- $dt = new DateTime();: Creates a new DateTime object representing the current date and time.
- $dt->sub(new DateInterval('P1D'));: Subtracting one day from the DateTime object using the sub() method and a DateInterval of one day (P1D).
- echo $dt->format('F j, Y')."\n";: Formatting the modified date and time as "Month Day, Year" using the format() method with the 'F j, Y' format specifier, and then outputting it, followed by a newline character.
Flowchart :

For more Practice: Solve these Related Problems:
- Write a PHP script to calculate and display yesterday's date using strtotime() with a relative date string.
- Write a PHP function that returns yesterday's date in a customizable format.
- Write a PHP program to compare yesterday's date with a fixed date and output the difference in days.
- Write a PHP script to output yesterday's date and then convert it to a UNIX timestamp.
Go to:
PREV : Convert Month Number to Month Name.
NEXT : Current Date/Time for Australia/Melbourne.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.