0

I have been using php/ mysql for long time and i have been using unix_timestamp to store date,time values. I have created timestamp class to handle this kind of request. Source code is available on github.

By default, this class uses $_SERVER['REQUEST_TIME'] which is GMT timestamp, I believe.

My requirement are to find out Local timestamp in accordance with GMT and show to user. In other word, I need to find the local time of any user and difference with GMT in number of seconds using PHP

How do I implement these requirements in my class. Please help

Narayan Bhandari
  • 426
  • 3
  • 11

2 Answers2

1

DateTime allows you to easily accomplish this:

// Interpret the time as UTC
$timezone = new DateTimeZone('UTC');
$datetime = new DateTime('@' . $_SERVER['REQUEST_TIME'], $timezone);

// Output as PHP's timezone
$user_timezone = new DateTimeZone(date_default_timezone_get()); // Or whatever timezone you need
$datetime->setTimeZone($user_timezone);
echo $datetime->format('Y-m-d H:i:s');
Blizz
  • 8,082
  • 2
  • 33
  • 53
  • I got "2015-07-07 16:20:09" as result but, in my local time is "2015-07-08 02:20:09". How do i code my class so that the class would work for any region in world and prints local time – Narayan Bhandari Jul 07 '15 at 16:25
  • You change the part with the $user_timezone to the name of the users' timezone. You probably get that information from their account on your site, if you have them select a timezone. – Blizz Jul 07 '15 at 16:28
  • is there any way to find out without asking user? if possible in PHP otherwise in jquery or javascript. Coz once I know the difference, it can be stored in connection database – Narayan Bhandari Jul 07 '15 at 16:34
  • Seriously... https://www.google.com/search?q=javascript+determine+user+timezone You can at least do SOME effort. – Blizz Jul 07 '15 at 16:38
0

To get an UTC timestamp try:

date_default_timezone_set("UTC");
echo date("Y-m-d H:i:s", time()); 
kguest
  • 3,804
  • 3
  • 29
  • 31
  • I did as following : $test=new scTimestamp(); $test1= new scTimestamp(); date_default_timezone_set("UTC"); $time= time(); $test1->setTimestamp($time); echo $test->getDateTimeAsString(); echo $test1->getDateTimeAsString(); and get the same result: July 7, 2015, 4:10 pm July 7, 2015, 4:10 pm and my local time is July 8, 2015, 2:10 am – Narayan Bhandari Jul 07 '15 at 16:11