0

PHPs DateTime is not doing what I expect it to do here....

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! 
    }
}

In Auckland it is a Sunday, yet even when I explicitly change the TimeZone nothing changes, it still shows up as Saturday.

How do I get DateTime to change the date to match the timezone??

Furthermore, if passing the new DateTimeZone object into the DateTime object does absolutely nothing, then what is the point of passing it in the first place? This is really bugging me because I know I have got something completely wrong!

1 Answer 1

2

When you create DateTime second parameter is DateTimeZone of first parameter, when you want to change timezone of DateTime you need to do it after with method setTimezone.

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! 
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for clarifying, so why pass in a DateTimeZone in the first place if you have to manually override it later with setTimezone()?
If you have date like '2016-10-01 14:33:21' and you know that this is in timezone 'Europe/Prague' then you could simply do new DateTime('2016-10-01 14:33:21', new DateTimeZone('Europe/Prague')), and its correct.
manual override is needed only if you need to change timezone

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.