Hot Koehls
  • Email
  • Feedburner
  • Linkedin
  • Twitter
  • Home
  • About
  • Archives
  • Contact
  • Software
    • S3imple Backup
    • Twitter Feed Archiver
    • FileTime
    • Flickr API Demo
Search
Home» For techies » Easily calculate dates and times in different timezones

Easily calculate dates and times in different timezones

Posted by Frank - November 25, 2008 - For techies
2

Building off my last post, where I showed you how to easily display any public Twitter feed on your site, I ran into another problem: the dates that are delivered by the Twitter API all reflect Greenwich Mean Time (GMT). Now I thought about going the old route and doing some convoluted math using date(), strtotime(), and mktime(), but I thought it was time find a serious solution, one that would allow me to display the correct time for whatever timezone I wished.

So while searching the web, I came across an insightful post that discussed PHP’s built-in DateTime object. I try hard to keep up with all the tech in my job, but this one got through the cracks, and I was instantly intrigued. So after some research and fiddling, I came up with the following block of code, which will allow you to easily translate dates/times to and from any timezone.

date_default_timezone_set('GMT');
$datetime = new DateTime('2008-11-25 16:48:13');
$tz = new DateTimeZone('America/New_York');
$datetime->setTimezone($tz);
$time_display = $datetime->format('D, M jS g:ia T');

The process is a little convoluted, so here’s what’s going on. First we must set the system-wide timezone to match that of the date/time we would like to translate. In this example, it’s about 4:50pm on Nov 25, 2008 in the GMT timezone. Next we create a DateTime object with that time (FYI you can use any format accepted by strtotime()).

Next we create a DateTimeZone object. Keep in mind that this step stands completely on its own, and can be performed anytime up to now.

Finally, we pass the DateTimeZone object as the lone argument in a call to the setTimezone() method. This will change the timezone stored in $datetime from GMT to EST, and automatically update the date/time accordingly, which we output with a call to the format method.

Note that I used object-oriented syntax for this process, but there is a procedural style (i.e. functions) as well. I prefer OOP here because it’s just easier to read and follow.

Valid arguments for date_default_timezone_set() and DateTimeZone() come from PHP’s list of supported timezones.

So now that we can translate timezones, let’s apply it to my Twitter example…

    status as $key => $status) { $datetime = new DateTime($status->created_at); $datetime->setTimezone($tz); $time_display = $datetime->format('D, M jS g:ia T'); ?>
  • text . '' . $time_display; ?>
  • more...

Sidenote: While I was working on this I found GMT and UTC used almost interchangeably. For all intents and purposes, they are identical. But there is a technical difference: GMT is based on the rotation of the earth (less precise), while UTC is based on an atomic clock (more precise). Don’t worry, you and I are not the only ones who got confused.

Build a slick Twitter feed on your site

  1. Display Twitter updates on your website
  2. Calculate dates and times in different timezones (translate Twitter timestamps)
  3. Parse URL’s in text, create links
extension, fwdvault, programming, standards

2 comments on “Easily calculate dates and times in different timezones”

  1. Godfried says:
    December 29, 2008 at 2:14 pm

    Hi Frank,

    Thanks for your post.
    I made a function from your post that outputs a the time in another timezone with a give time in another timezone.:

    function time_in_other_tz($source_time,$source_tz,$destination_tz) {

    $currentTimeZone = date_default_timezone_get();
    date_default_timezone_set($source_tz);
    $datetime = new DateTime($source_time);
    $tz = new DateTimeZone($destination_tz);
    $datetime->setTimezone($tz);
    $toReturn = $datetime->format(‘Y-m-d H:i:s’);
    date_default_timezone_set($currentTimeZone);

    return $toReturn;
    }

    $source_time = “2008-12-29 19:10:20″;
    $source_tz = ‘Europe/Amsterdam’;
    $destination_tz = ‘Europe/Moscow’;

    echo time_in_other_tz($source_time,$source_tz,$destination_tz);

  2. Frank says:
    January 6, 2009 at 12:43 pm

    Nice job! The ability to “function-ize” a given code snippet is always a clear sign that someone has grasped the concept(s) at work. This is precisely why I usually don’t provide functions, opting instead for blocks of code that people can read, understand, and then apply.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Categories

  • For entrepreneurs
  • For everyone
  • For techies

Latest Tweets

  • The word traps planners plan themselves into | Life. Then strategy http://t.co/iANAdASb
    May 8, 2012 - 2:43 pm
  • Random network security tip for those about to appear on TV - Boing Boing http://t.co/tC1lXFQ4
    May 8, 2012 - 1:42 pm
  • A Picture http://t.co/H846Uy69
    April 27, 2012 - 12:25 pm
  • The Broken "Buy-One, Give-One" Model: 3 Ways to Save Toms Shoes | Co.Exist: World changing ideas and innovation http://t.co/RI0sVMW6
    April 10, 2012 - 12:23 pm

Recent Comments

  • whiz on What 255 characters looks like
  • Andrew on Find the second (or third, or fourth) occurence in a string
  • IanArcher on Get number of message parts in an email using PHP
  • Usama on Remove parent directories from tar archives
  • Frank on It’s dangerous to go alone

Recent Posts

  • It’s dangerous to go alone
  • Create Self-Signed Wildcard SSL Certificate
  • What comes after the yottabyte?
  • Write code like they do in Hollywood
  • Brian Rolle machine gun celebration
(c) 2012 Frank Koehl. All Rights Reserved.
  • Contact Us
  • Sitemap