DateTime in php with timezone

Harea Costicla picture Harea Costicla · Dec 1, 2016 · Viewed 24.3k times · Source

I have a question. I try to use datetime in php. I did :

$now = new \DateTime();

When I print_r the $now I have :

DateTime Object
(
  [date] => 2016-12-01 05:55:01
  [timezone_type] => 3
  [timezone] => Europe/Helsinki
)

When I look at clock I have 16:05. I need to set the timezone ? I want to use Bucharest timezone. How I can get the right date and hour ? Thx in advance

Answer

Karol Gasienica picture Karol Gasienica · Dec 1, 2016

You have two ways to set right timezone. It is object way and procedural way.


Examples

Object

$datetime = new DateTime();
$timezone = new DateTimeZone('Europe/Bucharest');
$datetime->setTimezone($timezone);
echo $datetime->format('F d, Y H:i');

Procedural

date_default_timezone_set("Europe/Bucharest");
$date = date('F d, Y H:i');
echo $date;

Manuals


Update

Check code below, may it will work for you:

<?php
date_default_timezone_set('Europe/London');
$datetime = new DateTime();
$timezone = new DateTimeZone('Europe/Bucharest');
$datetime->setTimezone($timezone);
echo $datetime->format('F d, Y H:i');
?>