[英]How to set time zone with DateTime object?
我創建了一個在服務器文件夾中打印日志的代碼,這個日志還返回一個帶有小時的日期,但服務器不在我的國家,所以小時對我來說是不正確的。 其實這是我的代碼:
$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);
如何為意大利設置正確的小時?
$date = new DateTime('now',new DateTimeZone("Europe/Rome"));
您也可以在文件的頂部執行此操作,例如:
date_default_timezone_set('Europe/Rome');
您可以在構造函數中將其設置為第二個參數
$date = new DateTime(null, new DateTimeZone('Europe/Rome'));
或者稍后使用setTimezone
函數
$date = new DateTime();
$date->setTimezone(new DateTimeZone('Europe/Rome'));
您可以在http://php.net/manual/en/datetime.settimezone.php上閱讀更多相關信息
在PHP中使用時區非常簡單。 下面是一個例子:
// 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";
參考:
PHP手冊 - DateTimeZone
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.