2016-10-01 3 views
0

PHPS DateTimeのは、それが日曜日で、まだ私は明示的にタイムゾーンを変更しても....私はそれがここで行うことを期待するものオークランドでトラブル:PHPのDateTimeは

class Time_model extends CI_model 
{ 
    public $time_zone; 
    public $tz; 
    public $dt; 

    public function __construct() 
    { 
     date_default_timezone_set('UTC'); 
     $this->time_zone = 'Pacific/Auckland'; 

     $this->tz = new DateTimeZone($this->time_zone); 
     $this->dt = new DateTime('now', $this->tz); 
    } 

    /** 
    * dates 
    */ 

    public function getDate() 
    { 
     $this->dt->getTimezone(); // <--- shows that the timezone is auckland where it is the 02/10/2016 
     return $this->dt->format('Y-m-d'); // <--- yet returns the 01/10/2016! 
    } 
} 

をやっていない、間違った日付を返します何も変わらず、それはまだ土曜日に現れます。

タイムゾーンと一致するように日付を変更するにはどうすればよいですか?

さらに、新しいDateTimeZoneオブジェクトをDateTimeオブジェクトに渡すことは絶対に何もしない場合、最初にそれを渡すのは何ですか?私は何かが完全に間違っていることを知っているので、これは本当に私を悩ましています!

答えて

2

あなたはDateTime二番目のパラメータを作成するには、DateTimeのタイムゾーンを変更したいときは、この方法setTimezoneとした後、それを実行する必要があり、最初のパラメータのDateTimeZoneです。

class Time_model extends CI_model 
{ 
    public $time_zone; 
    public $tz; 
    public $dt; 

    public function __construct() 
    { 
     $this->time_zone = 'Pacific/Auckland'; 

     $this->tz = new DateTimeZone($this->time_zone); 
     $this->dt = new DateTime('now', new DateTimeZone("UTC")); 
     $this->dt->setTimezone($this->tz); 
    } 

    /** 
    * dates 
    */ 

    public function getDate() 
    { 
     $this->dt->getTimezone(); // <--- shows that the timezone is auckland where it is the 02/10/2016 
     return $this->dt->format('Y-m-d'); // <--- yet returns the 01/10/2016! 
    } 
} 
+0

なぜ、あとでsetTimezone()で手動でオーバーライドする必要がある場合は、最初にDateTimeZoneを渡すのですか? –

+0

'2016-10-01 14:33:21'のような日付があり、これがタイムゾーン 'Europe/Prague'にあることがわかっている場合は、単純に 'new DateTime( '2016-10-01 14:33: 21 '、新しいDateTimeZone(' Europe/Prague ')) '、およびその正しい。 –

+1

タイムゾーンを変更する必要がある場合にのみ手動オーバーライドが必要です –