开发者

Dealing with Timezones and Dates in PHP

开发者 https://www.devze.com 2023-02-23 12:02 出处:网络
I am running a service hosted on a server in the US which reads an XML feed that has been created with a local date - currently just the UK, but I want to ensure the service works with all timezones.

I am running a service hosted on a server in the US which reads an XML feed that has been created with a local date - currently just the UK, but I want to ensure the service works with all timezones. My process looks at the date of a post in a feed and compares it with the date/time right now(on the server in the US). The solution I came up with localises the system to the originator of the feed and then creates a timestamp with whi开发者_JAVA技巧ch to compare 'now' with:

protected function datemath($thedate){

    $currenttimezone = date_default_timezone_get();
    date_default_timezone_set($this->feedtimezone);
    $thedate = mktime substr($thedate,11,2),substr($thedate,14,2),
    substr($thedate,17,2),substr($thedate,3,2),substr($thedate,0,2),
    substr($thedate,6,4));
    date_default_timezone_set($currenttimezone);
    return $thedate;

    }

My question is this... Is this a reasonable way of handling this issue or is there a better, more standardized way that I really should know?


Here's a function I wrote to do timezone conversions. Should be pretty self-explanatory:

function switch_timezone($format, $time = null, 
    $to = "America/Los_Angeles", $from = "America/Los_Angeles")
{
    if ($time == null) $time = time();

    $from_tz = new DateTimeZone($from);
    $to_tz = new DateTimeZone($to);

    if (is_int($time)) $time = '@' . $time;

    $dt = date_create($time, $from_tz);

    if ($dt)
    {
        $dt->setTimezone($to_tz);
        return $dt->format($format);
    }

    return date($format, $time);
}


After a bit more checking of other peoples code I see the function

strtotime($thedate);

is a little bit more succinct than using mktime and also allows for different time formats.

0

精彩评论

暂无评论...
验证码 换一张
取 消