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.

12 comments












12 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.
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.
And don't forget about the kick-ass compare feature:
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
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
What excellent comments, thanks for all the additions and links. I think I learned some new things reading all these :)
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