Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Date() to something specific while script executes

Tags:

date

php

legacy

I have picked up some legacy code which uses date() all over the place. On the 31st of each month (if applicable) the script has a bug which I need to be able to replicate to fix. In order to do this I need the script to think that it is the 31st today.

Obviously I could parse the date and give it a string of the date that I want, but that would have to be on every instance of date() - which would be very difficult to change and I could miss one all to easily.

Is there a means therefore at the top of the script to specify what "Today's date" is? Or does date() get the date from the server each and every time, rendering this impossible?

Edit

For clarification this script is hosted on Azure App Services which means I can't change the time of the system unfortunately.

like image 875
tim.baker Avatar asked Feb 23 '26 08:02

tim.baker


1 Answers

There is an outdated pecl extension called apd which provides a function override_function() which does exactly what you want. Did not test it but it probably won't work anymore.

Another approach is so called monkey patching, making use of phps namespaces. See http://till.klampaeckel.de/blog/archives/105-Monkey-patching-in-PHP.html for example and explanation.

namespace myNameSpace;

function date($format, $timestamp = '') {
    echo 'Would have returned "' . \date($format, $timestamp) . '"';
}
echo date('d.m.Y', time());

As we are in namespace \myNameSpace php will first search for \myNameSpace\date() and use that instead of \date().

like image 84
maxhb Avatar answered Feb 25 '26 20:02

maxhb