fred2
fred2

Reputation: 1110

Why is my timezone setting not working?

I must be doing something stupid. The following code should create a timestamp relative to a set timezone string. However it always creates the timestamp relative to the server's default timezone instead.

        $this->timezone = "America/Edmonton";
        /*Server's default timezone is "America/Toronto"*/
        $n->sendTime = "13:25:00";

        $objTimeZone = new DateTimeZone($this->timezone);

        $objSendTime = new DateTime($n->sendTime);
        $objSendTime->setTimezone($objTimeZone);
        $sendTime = $objSendTime->getTimeStamp();

        $timeNow = time(); //Timestamps are all relative to UTC

        if (($timeNow - $sendTime) > 300 || ($timeNow - $sendTime) < 0){
            //Send time is not within last 5 minutes or is in future//
            echo "Don't Send!";
        }
        echo "Send!";

Expected behaviour: if the time is within 5 minutes of 13:25:00 Mountain Time, the code will echo "Send!";

Actual behaviour: if the time is within 5 minutes of 13:25:00 Eastern Time, the code echoes "Send!";

Can anybody explain to me why setTimezone() does not work as expected?

Upvotes: 0

Views: 66

Answers (1)

Chin Leung
Chin Leung

Reputation: 14921

The PHP Function Datetime::getTimeStamp gets the Unix timestamp of the system, which is why even though you change the variable timezone to Edmonton's Timezone, your $sendTime variable is still the time of Eastern Time.

As a proof, if you do $objSendTime->getTimestamp(), it would return 1456424700, which is the UNIX timestamp of 13:25:00.

You could do this instead, which would format the object's time to an appropriate time string and convert it into time with the built-in function strtotime:

$sendTime = strtotime($objSendTime->format('Y-m-d H:i:s'));

This would convert the appropriate time (11:25:00) instead of 13:25:00. Another option is to set the default timezone to Edmonton.

date_default_timezone_set('America/Edmonton');
$sendTime = $objSendTime->getTimestamp(); // 1456417500 (11:25:00)

Upvotes: 1

Related Questions