Getting Yesterday’s Date in PHP

by Terri Ann on July 2, 2009

It’s a blessing and a curse the way there are so many different methods to calculate things.

For instance calculating or retrieving yesterday’s date in PHP: I came up with 4 quick ways to calculate it.

I always remember method 1, using mktime() but decided to benchmark each of them to see which method of calculation is the most efficient.

I used date("Y-m-d") as a control in all the benchmarks since each of the yesterday calculations are using that function to display.

Note: I may not display my data in the standard programming benchmark styles but that’s because of the way I approach information. I would rather tell you what I learned from the data not just spit out the data and make you do all the thinking. Do you want hard data? Run your own tests. This is about knowledge – not data.

Method 1 – mktime()

echo date("Y-m-d", mktime(0, 0, 0, date("m"),date("d")-1,date("Y")));

This method was by far the slowest. Performing at 450% the time of the control.

Method 2 – Subtracting minutes from the current unix timestamp time()

echo date("Y-m-d", time() - 86400);
// I did not benchmark the following but this is how I would typically use this method:
echo date("Y-m-d", time() - (60*60*24) );

In the benchmark this was the fastest, performing at 103% of the control. Subtracting 86,400, ie. the number of minutes in a day, is accurate under normal circumstances though getting hours or any time during daylight savings time could get a little dicey. As always it depends on your needs.

Method 3 – strtotime() yesterday

echo date("Y-m-d", strtotime("yesterday"));

This is fast but what happens if you need to create a script where you may need to reuse yesterday to calculate the day before yesterday – there is no easy solution with this method, whereas the other 3 methods can either be added to, subtracted from or multiplied to calculate yesterday’s yesterday.

Method 4 – strtotime() -1 day

echo date("Y-m-d", strtotime("-1 day"));

I really like this method, though it’s not the fastest, performing at 203% the time of the control, it’s easily expandable and human readable, just change the 1 to another number or change the – to a + for tomorrow. Yes you can accomplish the same thing multiplying the 86400 in method 2 but it all depends on your style. I can’t easily skim a script and recognize 86400 as yesterday, so often I will use (60*60*24) instead which is as readable as -1 day for me.


As always- run your tests – see if one method is faster for you based on the conditions in your actual script or use what makes more sense to your scripts needs.

{ 1 comment… read it below or add one }

1 John Milmine July 7, 2009 at 9:32 pm

What about: $date = new DateTime(); $date->modify(‘-1 day’);

Leave a Comment

Previous post:

Next post: