0

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 which 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?

Stevo
  • 2,601
  • 3
  • 24
  • 32
  • Related question: http://stackoverflow.com/q/2532729/1583 – Oded Apr 07 '11 at 19:44
  • You're using mktime to break the time you get from the feed and date_default_timezone_set to make sure you get the corect number of seconds in regards to the feeds timezone? Yeah, pretty reasonable... – Khez Apr 07 '11 at 19:45
  • @Oden Wow - that's a pretty comprehensive answer. Clearly it is as much as a pain as I'm finding it to be. – Stevo Apr 07 '11 at 19:49

2 Answers2

1

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);
}
Jimmy Sawczuk
  • 13,488
  • 7
  • 46
  • 60
  • 1
    You can actually [stick a `@`](http://us2.php.net/manual/en/datetime.formats.compound.php) in front of the unix timestamp when passing it to the DateTime constructor / date_create. No need to jump through the formatting hoop. – Charles Apr 07 '11 at 19:46
  • Ah, no, I meant `if (is_int($time)) $time = '@' . $time;` – Charles Apr 07 '11 at 19:53
  • Corrected, is `date_create` just engineered that way, to accept timestamps prefixed by `@`? – Jimmy Sawczuk Apr 07 '11 at 19:56
  • 1
    Indeed, check out the link I posted in my original comment ("stick a @") for more information on accepted time and date formats. – Charles Apr 07 '11 at 19:59
0

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.

Stevo
  • 2,601
  • 3
  • 24
  • 32