简体   繁体   中英

How to set time zone with DateTime object?

I made a code that print a log in a server folder, this log return also a date with hours but the server isn't in my Nation so the hours is incorrect for me. Actually this is my code:

$now = new DateTime();  
$aggiornata = "\r\n" . "Aggiornamento eseguito con successo per: " . $value['caption'] . " DATA: " . $now->format('d-m-Y H:i:s');
file_put_contents(getenv('OPENSHIFT_REPO_DIR').'php/log.txt', $aggiornata, FILE_APPEND);

How to set the correct hour for Italy?

看看DateTimeZone

$date = new DateTime('now',new DateTimeZone("Europe/Rome"));

您也可以在文件的顶部执行此操作,例如:

date_default_timezone_set('Europe/Rome');

You can set it in constructor as second argument

$date = new DateTime(null, new DateTimeZone('Europe/Rome'));

or later with setTimezone function

$date = new DateTime();
$date->setTimezone(new DateTimeZone('Europe/Rome'));

You can read more about it here http://php.net/manual/en/datetime.settimezone.php

Working with timezones in PHP is pretty easy. Below follows an example:

// Create a new DateTime object
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));

// Output
echo $date->format('Y-m-d H:i:sP') . "\n";

// Change timezone
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));

// Output again
echo $date->format('Y-m-d H:i:sP') . "\n";

Reference:

PHP Manual - DateTimeZone

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