Method 1 –
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
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 –
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.