6

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

Harea Costicla
  • 797
  • 3
  • 9
  • 20

5 Answers5

23

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');
?>
Karol Gasienica
  • 2,825
  • 24
  • 36
11

There are examples in the manual, you can set the timezone on the instantiation of the DateTime class like this

$now = new \DateTime('now', new DateTimeZone('Europe/Bucharest'));
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
2

put this line of code above your script:

date_default_timezone_set('Europe/Bucharest');
kerv
  • 315
  • 1
  • 2
  • 13
1
<?php

    $datetime = new DateTime( "now", new DateTimeZone( "Europe/Bucharest" ) );

    echo $datetime->format( 'Y-m-d H:i:s' );

Demo repl.it

antelove
  • 3,216
  • 26
  • 20
0

You can use setTimezone() method of DateTime class to set the timezone to Europe/Bucharest, like this:

$now = new \DateTime();
$now->setTimezone(new DateTimeZone('Europe/Bucharest'));

Here's the reference:

Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37