vooD vooD - 1 year ago 58
PHP Question

Change today's date and time in php

Is it possible to change php's current date and time (something like set_time(strtotime('1999-09-09')) so when i call time() it will return me timestamp for 1999-09-09? I need to set it globally for whole app.


I already have one old app and i need to make possible to set up current date.
I can't accept any custom functions. Imagine i should review all the code and replace every time() call. Even if i'll do so then it will not help because there are functions like getdate() which i need to replace as well.

Answer Source

The time() functions actually asks the system clock for the time, so you'd have to update the time of the server's system clock. A few things to keep in mind:

  • This is done differently on a Unix server than a Windows server. If you want code compatible with both, you have to be careful
  • Sometimes (especially in shared hosting situations) you aren't allowed to change the system time
  • Changes to system time will remain after the script has executed unless you change it back later. Therefore you risk really screwing up the system clock.

If you want to change the time globally for an entire app, I recommend having a static variable $timeOffset and create your own time() function as follows:

function myTime(){
    global $timeOffset;
    return time()+$timeOffset;

If you've taken all of that into account and still want to change the system time, however, you would need to send a command to the shell using shell_exec()

In Windows, the code would look like this:

shell_exec("date 09-09-99"); // Use "date mm-dd-yy" or "time hh:mm:ss", respectively

In UNIX, according to the date man page, the code would look like:

shell_exec("date 0909hhmm1999"); // It says "date MMDDhhmiYYYY". I'm not sure how to set seconds, although I assume "mi" = "minutes"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download