Aliweb
Aliweb

Reputation: 1951

php date function showing wrong time

I've faced a really funny problem. my server timezone is set to America/New_York (as indicated in phpinfo() and return value of date_default_timezone_get()) and now it is 23:30 PM in New York but when use echo date(h:i) it shows me 7:30 AM , with 8 hours offset!

My server system time also shows 7:30 AM and default timezone is not set in php.ini

Thanks for your help

Upvotes: 1

Views: 8127

Answers (2)

Aliweb
Aliweb

Reputation: 1951

I myself found this article http://abdussamad.com/archives/343-CentOS-Linux:-Setting-timezone-and-synchronizing-time-with-NTP-.html really usefull in my case and worked fine for me.

As other friends mentioned , the server time should be corrected and synchronized with the server timezone.

Upvotes: 0

maček
maček

Reputation: 77816

Sounds simple.

Based on the comments to your question, fix the time on the server and PHP will report the correct time.

If your server is set in America/New_York timezone and PHP is also set to America/New_York, that is, if the server offset matches PHP's offset, PHP will just output the server's time.

It's possible you were assuming that PHP's date() function is getting the current time from a time server or something; This is not the case.

Bonus

After writing the last part of my answer, I felt like figuring out how get time from an NTP time server, e.g., time.apple.com

<?php 

function ntp_time($host) {

  // Create a socket and connect to NTP server
  $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
  socket_connect($socket, $host, 123);

  // Send request
  $msg = "\010" . str_repeat("\0", 47);
  socket_send($socket, $msg, strlen($msg), 0);

  // Receive response and close socket
  socket_recv($socket, $recv, 48, MSG_WAITALL);
  socket_close($socket);

  // Interpret response
  $data = unpack('N12', $recv);
  $timestamp = sprintf('%u', $data[9]);

  // NTP is number of seconds since 0000 UT on 1 January 1900
  // Unix time is seconds since 0000 UT on 1 January 1970
  $timestamp -= 2208988800; 

  return $timestamp;
}

// Get America/New_York time from time.apple.com
date_default_timezone_set('America/New_York');
echo date('Y-m-d H:i:s', ntp_time('time.apple.com'));
//=> 2012-11-25 23:59:02

Upvotes: 4

Related Questions