PHP: how to read current date / time from server and not from php.ini

Here's my problem:

echo date('Y-m-d H:i:s'); 
echo date('Y-m-d H:i:s', mktime());  

echo exec('date');



2012-03-21 08:45:51
2012-03-21 08:45:51

Wed Mar 21 10:45:51 EDT 2012


Server time is off for 2 hours since php date () returns; or any other php date / time function. This is because the server time is set to EST and PHP.INI date.timezone = "America / Denver"

I need to keep the two in sync using date_default_timezone_set, but I don't know in advance what the difference is.

Is there any other way to get the local server time besides calling exec?

UPD: I know the php.ini setting is wrong and I can change it. The problem is this script will work and no one knows which servers. I can't go to each one and fix the php.ini file. I also don't know in advance what timezone will be on these servers. I need a dynamic solution that will work everywhere.


source to share

4 answers

you can change ini timezone and print date

ini_set('date.timezone', 'America/Los_Angeles');




Change value of date.timezone from php.ini [Date] and restart your server.
You can get your date.timezone value form-

For Bangladesh I set in my php.ini [Date]
date.timezone = Asia/Dhaka

You get your php.ini in C:\xampp\php address for XAMP server and Windows.





some hosts give you the ability to edit php.ini

find php config




On * nix, you can use the formatting options for date

to get what you need:

  • date +%z

    - time zone (hhmm)
  • date +%:z

    - time zone (hh: mm)
  • date +%z

    - abbreviation of the time zone abbreviation (for example, "EDT")

Making a system call (for example echo exec('date +%z');

) bypasses any INI settings by date_default_timezone_get . Note that this function will emit E_WARNING if it is read from the system time, and indeed from PHP 5.4 it does not even allow reading from it - in particular, because it cannot be relied on.

To be consistent regardless of your server settings, you must use UTC in your application. For ease of use, GMT is close enough to UTC for most purposes, so you can use gmdate()




All Articles