Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php get US/Eastern current time

Tags:

php

I want to get current time of US/Eastern timezone. How would I achieve that.

I have tried following code but it is displaying my system's time.

<?php
   date_default_timezone_set('US/Eastern');
   $currenttime = date('h:i:s:u');
   list($hrs,$mins,$secs,$msecs) = split(':',$currenttime);
   //print "&time2=".$secs."&time1=".$mins."&time0=".$hrs;
?>

I am using this script with flash so commented out 'print' line.

like image 332
booota Avatar asked Dec 16 '10 00:12

booota


People also ask

What is PHP time zone?

The default timezone for PHP is UTC regardless of your server's timezone. This is the timezone used by all PHP date/time functions in your scripts.

What PHP function do you call to get the current time stamp?

The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

How do I set default timezone?

The date_default_timezone_set() function sets the default timezone used by all date/time functions in the script.


2 Answers

<?php
   echo date_default_timezone_get();
   $currenttime = date('h:i:s:u');
   list($hrs,$mins,$secs,$msecs) = split(':',$currenttime);
   echo " => $hrs:$mins:$secs\n";

   date_default_timezone_set('US/Eastern');
   echo date_default_timezone_get();
   $currenttime = date('h:i:s:u');
   list($hrs,$mins,$secs,$msecs) = split(':',$currenttime);
   echo " => $hrs:$mins:$secs\n";

   date_default_timezone_set('America/New_York');
   echo date_default_timezone_get();
   $currenttime = date('h:i:s:u');
   list($hrs,$mins,$secs,$msecs) = split(':',$currenttime);
   echo " => $hrs:$mins:$secs\n";

?>

Seems to work here (in Berlin):

Europe/Berlin => 01:42:42
US/Eastern => 07:45:18
America/New_York => 07:45:18
like image 166
miku Avatar answered Sep 20 '22 15:09

miku


$amNY = new DateTime('America/New_York');
$estTime = $amNY->format('h:i:s:u');

or if you are using php 5.4 and above

estTime = (new DateTime('America/New_York'))->format('h:i:s:u');

date_default_timezone_set() will affect the whole script and should be used carefully

like image 38
Sajeev Nair Avatar answered Sep 23 '22 15:09

Sajeev Nair