[php] How to get date and time from server

I want to retrieve date and time from server and according to it do some thing. For this I used following code:

$info = getdate();
$date = $info['mday'];
$month = $info['mon'];
$year = $info['year'];
$hour = $info['hours'];
$min = $info['minutes'];
$sec = $info['seconds'];

$current_date = "$date/$month/$year == $hour:$min:$sec";

This code returns proper date but problem is that what I see in my cpanel(server time) is diff. than what I get from code. In cpanel time is CDT while from code it is showing UTC which I reconfirm using following code

<?php echo date("r == e"); ?>

Why this is happening and what changes I have to do in my code so that I can get proper server time.

This question is related to php datetime

The answer is


Try this -

<?php
date_default_timezone_set('Asia/Kolkata');

$timestamp = time();
$date_time = date("d-m-Y (D) H:i:s", $timestamp);
echo "Current date and local time on this server is $date_time";
?>

For enable PHP Extension intl , follow the Steps..

  1. Open the xampp/php/php.ini file in any editor.
  2. Search ";extension=php_intl.dll"
  3. kindly remove the starting semicolon ( ; ) Like : ;extension=php_intl.dll. to. extension=php_intl.dll.
  4. Save the xampp/php/php.ini file.
  5. Restart your xampp/wamp.

No need to use date_default_timezone_set for the whole script, just specify the timezone you want with a DateTime object:

$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London'));    // Another way
echo $now->format("Y-m-d\TH:i:sO"); // something like "2015-02-11T06:16:47+0100" (ISO 8601)

You should set the timezone to the one of the timezones you want. let set the Indian timezone

// set default timezone
date_default_timezone_set('Asia/Kolkata');

$info = getdate();
$date = $info['mday'];
$month = $info['mon'];
$year = $info['year'];
$hour = $info['hours'];
$min = $info['minutes'];
$sec = $info['seconds'];

$current_date = "$date/$month/$year == $hour:$min:$sec";

You can use the "system( string $command[, int &$return_var] ) : string" function. For Windows system( "time" );, system( "time > output.txt" ); to put the response in the output.txt file. If you plan on deploying your website on someone else's server, then you may not want to hardcode the server time, as the server may move to an unknown timezone. Then it may be best to set the default time zone in the php.ini file. I use Hostinger and they allow you to configure that php.ini value.


You have to set the timezone, cf http://www.php.net/manual/en/book.datetime.php