简体   繁体   English

如何使用DateTime对象设置时区?

[英]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 或者稍后使用setTimezone函数

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

You can read more about it here http://php.net/manual/en/datetime.settimezone.php 您可以在http://php.net/manual/en/datetime.settimezone.php上阅读更多相关信息

Working with timezones in PHP is pretty easy. 在PHP中使用时区非常简单。 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 PHP手册 - DateTimeZone

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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