DateTime in php with timezone
Asked Answered
P

5

7

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

Promissory answered 1/12, 2016 at 14:6 Comment(0)
C
24

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');
?>
Catcall answered 1/12, 2016 at 14:20 Comment(4)
It gives December 01, 2016 16:35, and that's time in Bucharest now.Catcall
I got December 01, 2016 06:25 Promissory
Garsienica, not work :( I got December 01, 2016 06:29Promissory
Strange... it works there: sandbox.onlinephpfunctions.com/code/…Catcall
C
12

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'));
Consulate answered 1/12, 2016 at 14:12 Comment(8)
I have this : DateTime Object ( [date] => 2016-12-01 06:09:43 [timezone_type] => 3 [timezone] => Europe/Bucharest ) Promissory
But the hour now is 16:22Promissory
The time in Bucharest is 16:22 @ UTC 14:22Consulate
Where are you located?Consulate
Then you are doing something else other than what you have shown us to the $now variableConsulate
I use a virtual machine, and this machine have linuxPromissory
And this machine have : Thu Dec 1 06:32:44 EET 2016Promissory
it's a way to get the date not depending OSPromissory
B
2

put this line of code above your script:

date_default_timezone_set('Europe/Bucharest');
Barter answered 1/12, 2016 at 14:8 Comment(0)
T
1
<?php

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

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

Demo repl.it

Teddi answered 24/12, 2020 at 14:33 Comment(0)
B
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:

Blackman answered 1/12, 2016 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.