I'm writing a PHP system and I need to get the system time. Not the GMT time or the time specific to a timezone, but the same system time that is used by the CRON system. I have a CRON job that runs every day at midnight and I want to show on a webpage how long will it take before it runs again.
For example: Right now it is 6pm on my system clock. I run the code:
$timeLeftUntilMidnight = date("H:i", strtotime("tomorrow") - strtotime("now"));
The result, however, is "3:00" instead of "6:00". If I run
date("H:i", strtotime("tomorrow"));
It returns 0:00, which is correct. But if I run
date("H:i", strtotime("now"));
It returns 21:00, even though the correct should be 18:00.
Thanks.
There are many answers, however there is not even one correct at the time of writing.
PHP time()
function doesn't return the system time, like most folks believe, but it return the PHP localtime, normally set with date.timezone
in php.ini, or set with date_default_timezone_set()
within a script.
For instance in one of my servers, PHP time was set to Europe/Rome
and system time to UTC
. I had a difference of one hour between system time and PHP time.
I'm going to give you a solution that works for Linux, I don't know for Windows. In Linux the system timezone is set in /etc/timezone
. Now, this is normally outside my allowed open_basedir
setting, but you can add :/etc/timezone
to your list to be able to read the file.
Then, on top of the scripts, that want to get the system time, you can call a library function that sets the script timezone to the system timezone. I suppose that this function is part of a class, so I use static:
static function setSystemTz() {
$systemTz = trim(file_get_contents("/etc/timezone"));
if ($systemTz == 'Etc/UTC') $systemTz = 'UTC';
date_default_timezone_set($systemTz);
}
To make the matter worse in PHP 5.3.3 'Etc/UTC' is not recognized, while 'UTC' is, so I had to add an if to fix that.
Now you can happily call time()
and it will really give you the system time. I've tested it, because I needed it for myself, that's why I found this question now.
php's time
will return the system time. you can format it with date
if you just want to display the time in the local time of the visitor maybe you're better off using a little javascript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With