I have attempted to do this using the following code:
$date = new DateTime('now');
$datePST = $date->setTimezone(new DateTimezone('PST'));
$dateEST = $date->setTimezone(new DateTimezone('EST'));
echo $date->format('H:i:s');
echo '<br />';
echo $EST = $dateEST->format('H:i:s');
echo '<br />';
echo $PST = $datePST->format('H:i:s');
But they all output the same time. Why are they not outputting the correct times?
Because they are all pointing to the same object. So when you change the timezone in one you are changing it for all of them.
$date = new DateTime('now');
echo $date->format('H:i:s');
echo '<br />';
$date->setTimezone(new DateTimezone('PST'));
echo $date->format('H:i:s');
echo '<br />';
$date->setTimezone(new DateTimezone('EST'));
echo $date->format('H:i:s');
If you want to have separate variables for each timezone you can use clone
to create new objects:
$date = new DateTime('now');
$datePST = clone $date;
$datePST = $datePST->setTimezone(new DateTimezone('PST'));
$dateEST = clone $date;
$dateEST = $dateEST->setTimezone(new DateTimezone('EST'));
echo $date->format('H:i:s');
echo '<br />';
echo $EST = $dateEST->format('H:i:s');
echo '<br />';
echo $PST = $datePST->format('H:i:s');
If you're using PHP 5.5 you can use the new DateTimeImmutatable()
class as well:
$date = new DateTimeImmutable('now');
$datePST = $date->setTimezone(new DateTimezone('PST'));
$dateEST = $date->setTimezone(new DateTimezone('EST'));
FYI, using "now"
is unnecessary as when no parameter is passed to DateTime()
it automatically defaults to the current date and time..