129

Possible Duplicate:
Get timestamp of today and yesterday in php

I was wondering if there was a simple way of getting yesterday's date through this format:

date("F j, Y");
Community
  • 1
  • 1

3 Answers3

233

date() itself is only for formatting, but it accepts a second parameter.

date("F j, Y", time() - 60 * 60 * 24);

To keep it simple I just subtract 24 hours from the unix timestamp.

A modern oop-approach is using DateTime

$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";

Or in your case (more readable/obvious)

$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";

(Because DateInterval is negative here, we must add() it here)

See also: DateTime::sub() and DateInterval

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • 3
    very good answer, there are many ways to do it but you have the simple one, short and easy to understand ( + the OOP one for those interested in using more RAM ;) – neofutur Apr 12 '12 at 08:04
  • 3
    @neofutur Beside "we want to waste our RAM" the OOP-approach is useful, when you already have either a `DateTime`-, or a `DateInterval`-object (or both), which may be the case in an OOP-based application (e.g. `$customer->expire->add(DateInterval::createFromDateString('+1 year')) // customer paid for one additional year`) Also note, that `DateInterval` understands ISO8601 for time intervals, but `date()` doesn't. At the end of course: Select the one you better fit your needs :) – KingCrunch Apr 12 '12 at 08:19
  • 13
    This is NOT a correct answer!! Daylight savings makes 23 and 25 hour days. So this is NOT giving you a good answer 2 hours of the year!!! – patrick Apr 24 '13 at 15:25
  • 3
    @patrick Interesting point :) Yes, you are right, but this is only true for the first solution, not the following utilizing `DateInterval`. – KingCrunch Apr 25 '13 at 14:26
  • $yesterday = strtotime("-1 day", $today); – nerkn Mar 05 '14 at 09:32
  • 2
    Don't forget to use it as `\DateTime` and `\DateInterval` in the context of a namespace. – Thomas Kekeisen Apr 21 '17 at 09:30
145

strtotime(), as in date("F j, Y", strtotime("yesterday"));

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
111

How easy :)

date("F j, Y", strtotime( '-1 days' ) );

Example:

echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43

Output:

2018-07-17 07:02:43
Vijay Verma
  • 3,660
  • 2
  • 19
  • 27
  • 6
    I prefer this answer. The offset ('-1') doesn't have to be a constant: it can be built with a variable,even with a loop: `strtotime( '-'.$s.' days' )` where `$s` is how many days back (or forward if playing with signs) you want to go. – Henry Mar 25 '13 at 03:04
  • i needed five days ago so this one is easiest to modify. – omikes Mar 27 '18 at 15:43
  • 1
    Use `Y-m-d` instead of `Y-m-j` for the ISO standard date, `j` doesn't have a leading zero. – toster-cx Feb 14 '19 at 16:30