Lorna Mitchell

Recently we published a post about tips for dates and times in PHP, today I thought I'd follow on from Michael and add some more tips. In PHP 5.2 there is an object oriented approach to working with dates and times - the DateTime class! In the newer PHP 5.3 versions even more excellent functionality was added. This is a short post to introduce this functionality with a focus on the methods available in PHP 5.2 showing some simple examples of how we can more easily manipulate and display dates without needing to work with timestamps.

Creating a DateTime Object

The DateTime class can accept any argument understood by the function strtotime() and turn it into an object that we can work with. This means that we can use almost any format and supply it to the constructor, e.g.:

$datetime = new DateTime('2010-05-03 17:26:32');

One thing which the manual doesn't show you is that you can also create using a timestamp, very useful if you are working with them already, perhaps you store datetimes that way or accept them as incoming parameters in that format. To do that you can use the following syntax:

$datetime = new DateTime("@{$timestamp}");

(where $timestamp is a unix timestamp). It is also possible to set the timestamp of an existing DateTime object using the setTimestamp() method of the class.

Timezones and DateTime

Since we are now representing our point in time with an object, we can store multiple pieces of information about it really easily. In particular we can store a timezone against the object, using the method DateTime::setTimezone(). The timezones themselves are also an object - of type DateTimeZone and represent timezones such as "Europe/Amsterdam" or "America/Lima". These will throw an exception if they receive a string they don't recognise into their constructor.

Very Easy Formatting

All our existing experience of working with dates in PHP will still be very useful to us working with the DateTime objects since to output our datetime value in a human-readable format, we use the DateTime::format() method - and this accepts the same arguments as the date() method does, so it will look quite familiar! There are some nice additions though, for example some constants that allow us to very easily output the correct format for all sorts of uses. A good illustration is the time format for cookies, which we would output something like this:

echo $datetime->format(DATE_COOKIE);

Unambiguous Storage

Storing the serialised DateTime objects is a great way to avoid the uncertainties that can arise between storing dates and times and using them on machines with different timezones used locally. It was actually solving a problem like this that I first started using this class so frequently. For more information about the problems (and solutions) around accurate date storage, I recommend Derick Rethans' blog post Storing Date/Times in Databases - its an excellent read and explains this issue in some detail.

Have you started using the DateTime class in PHP? I'm interested to know who is using it, or not, and why.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Plus

12 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Excellent post. A couple things I noted: first, it seems that DateTime automatically converts a timestamp to GMT. For example, when i create a timestamp in the eastern timezone, the date() function formats it in the correct time, while the DateTime::format() method shows the timestamp four hours ahead of Eastern time.

    Also, I've run into trouble in the past serializing DateTime objects. That's not to say it can't be done (and I have done it), but the built-in PHP objects don't always serialize well so it's important to test well and make sure things work the way they're supposed to.

  2. And don't forget about the kick-ass compare feature:

    <?php
    $dateA = new DateTime('yesterday');
    $dateB = new DateTime('tomorrow');
    if ($dateB > $dateA) {
        // yay, tomorrow happens after yesterday
    } else {
        // someone call the Aztecs!
    }
    ?>
  3. Watch out - these two are NOT equivalent, they result in different timezones!

    $d = new DateTime(); $d->setTimestamp($t);

    $d = new DateTime('@' . $t);

    "The $timezone parameter and the current timezone are ignored when the $time parameter […] is a UNIX timestamp." http://www.php.net/manual/en/datetime.construct.php

  4. Notably absent from the documentation is a link to the GNU page about date input formats. All possible time formats are explained over there: http://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html

  5. Lorna Mitchell said

    What excellent comments, thanks for all the additions and links. I think I learned some new things reading all these :)

  6. Ingo Ratsdorf said

    Actually, the above example from Mark van der Velden does **NOT** work in PHP 5.2.
    The comparsion does *ALWAYS* return false in PHP 5.2. Very annoying and dangerous.

Continuing the Discussion

  1. Webby Scripts Tips for Working with DateTime in PHP – techPortal linked to this post on May 4, 2010

    [...] original here: Tips for Working with DateTime in PHP – techPortal [...]

  2. Tips for Working with DateTime in PHP linked to this post on May 4, 2010

    [...] we can more easily manipulate and display dates without needing to work with timestampsMore here: Click Here…Read Other Interesting Posts in PHP TutorialsMy Clojure EditorBarcode HelperGoogleChart API [...]

  3. Ibuildings techPortal: Tips for Working with DateTime in PHP | Development Blog With Code Updates : Developercast.com linked to this post on May 4, 2010

    [...] the latest post from the Ibuildings techPortal Lorna Mitchell takes a look at one of the more powerful features included in PHP versions 5.2 and greater - the DateTime class. [...]

  4. Webs Developer » Ibuildings techPortal: Tips for Working with DateTime in PHP linked to this post on May 4, 2010

    [...] the latest post from the Ibuildings techPortal Lorna Mitchell takes a look at one of the more powerful features included in PHP versions 5.2 and greater – the DateTime [...]

  5. snippets, codigos, enlaces y recursos varios linked to this post on May 7, 2010

    [...] Tips para trabajar con la class DateTime en PHP http://techportal.ibuildings.com/2010/04/29/tips-for-working-with-datetime-in-php/ [...]

  6. Max’ Lesestoff zum Wochenende | PHP hates me - Der PHP Blog linked to this post on May 8, 2010

    [...] Tips for Working with DateTime in PHP – techPortal Ein paar Tips für die Verwendung von dem DateTime Object.. Welches Diagramm kann man für eine Präsentationsfolien nehmen? Nette Zusammenfassung, welches Diagramm man bei welchen Daten nehmen sollte … Max Stockner [...]

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.