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.:

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:

(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:

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.