Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime in php with timezone

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

like image 333
Harea Costicla Avatar asked Dec 01 '16 14:12

Harea Costicla


People also ask

How can we convert the time zones using PHP?

php $time='6:02'; $dt = new DateTime($time, new DateTimeZone('America/New_York')); //echo $dt->format('Y-m-d H:i:s') . PHP_EOL; $dt->setTimezone(new DateTimeZone('Asia/Kolkata')); echo $dt->format('H:i') .

What is PHP default timezone?

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.


2 Answers

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

  • PHP: date
  • PHP: DateTime
  • PHP: DateTimeZone

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');
?>
like image 58
Karol Gasienica Avatar answered Oct 13 '22 11:10

Karol Gasienica


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'));
like image 23
RiggsFolly Avatar answered Oct 13 '22 12:10

RiggsFolly