简体   繁体   中英

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

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

手册中示例,您可以像这样在 DateTime 类的实例化上设置时区

$now = new \DateTime('now', new DateTimeZone('Europe/Bucharest'));

把这行代码放在你的脚本之上:

date_default_timezone_set('Europe/Bucharest');

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:

<?php

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

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

Demo repl.it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM