w3resource

PHP Date Exercises : Get yesterday's date

PHP date: Exercise-13 with Solution

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 :

Flowchart: Get yesterday's date

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP script to change month number to month name.
Next: Write a PHP script to get the current date/time of 'Australia/Melbourne'.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.