DateTime in php with timezone

徘徊边缘 提交于 2019-12-11 02:42:12

问题


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


回答1:


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');
?>



回答2:


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'));



回答3:


put this line of code above your script:

date_default_timezone_set('Europe/Bucharest');



回答4:


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:

  • http://php.net/manual/en/datetime.settimezone.php


来源:https://stackoverflow.com/questions/40912701/datetime-in-php-with-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!