How to make PHP use my system time

Vipin Kumar
Vipin Kumar used Ask the Experts™
on
Hi,

Is it possible to to make PHP use server date and time instead of the timezone mentioned in php.ini file, i.e. if I change my server's date and time it should automatically use the same date and time.

Thanks in advance.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2011
Top Expert 2016
Commented:
You can do this with a DateTimeZone object that establishes the preferred timezone.  You use the object as an injected dependency when you create an instance of the DateTime object.
$zoneobj = new DateTimeZone('America/New_York');
$dateobj = new DateTime('NOW', $zoneobj);

Open in new window

You can also do this by calling the date_default_timezone_set() function in procedural code.

I am not sure how to ask the server to tell you the timezone (I do it the other way around - I give commands to the server instead of asking the server to tell me something), but if you can find that, these techniques will work.
Most Valuable Expert 2011
Top Expert 2016

Commented:
Looking a bit more for ways to ask the server for its current date/time, you might be able to use exec() and run the date command.  Full disclosure: I have never tested this, nor even thought about it very much!
http://stackoverflow.com/questions/18458839/how-to-get-the-current-date-and-time-in-the-terminal-and-set-a-custom-command-in
Dave BaldwinFixer of Problems
Most Valuable Expert 2014

Commented:
Windows servers use 'local time' but Linux servers do not use local time, their clocks are almost always set to GMT (Greenwich Mean Time) or Europe/London which is essentially the same thing.  Software running on Linux is expected to set their timezone to get the correct local time.
you can read the system's timesone from /etc/timezone or possibly $ENV['TZ'] and then use what ray posted or possibly ini_set the timezone or use the default_timezone_set() function so the regular date commands will behave like you want.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial