Cool DateTime Functions In PHP 5.3
Out Of Date Warning
Languages change. Perspectives are different. Ideas move on. This article was published on January 25, 2010 which is more than two years ago. It may be out of date. You should verify that technical information in this article is still current before relying upon it for your own purposes.
Over time, the PHP DateTime object has become one of the best objects available to PHP developers. This object has grown since early PHP 5 into a robust class that has the ability to do lots of great things.
Recently, I was exploring some of the functionality provided by the DateTime object as of PHP 5.3 (and wishing that Ubuntu had PHP 5.3 as a package distribution). Here are some of the new things in PHP 5.3 that are really cool.
Note: you can read the manual on the DateTime object here.
DateTime::add() and DateTime::sub()
The add() and sub() methods are about adding or subtracting the number of days, months, years, etc. from a DateTime object. The interface is a bit clunky, requiring you to pass in a DateInterval object. However, this still provides an easy way to modify a DateTime object.
For example, let’s say we wanted to add 3 weeks to our DateTime object:
<?php $dt = new DateTime(); // Set to now. $dt->add(new DateInterval('PW3')); echo $dt->format('n/j/Y'); // Outputs 3 weeks from today's date. ?>
How is this an improvement over using the DateTime::modify() method? It improves on it in one specific way: it’s object-oriented. Rather than passing a string you have the ability to pass an object.
One of the coolest PHP 5.3 features introduced was the ability to diff two DateTime objects. This returns to you a DateInterval object, which contains the details of how different the objects are.
$dt1 = new DateTime('August 3rd, 2004'); $dt2 = new DateTime('August 10th, 2006'); var_dump($dt1->diff($dt2));
The result that you get looks like this:
public ‘y’ => int 2
public ‘m’ => int 0
public ‘d’ => int 7
public ‘h’ => int 0
public ‘i’ => int 0
public ‘s’ => int 0
public ‘invert’ => int 0
public ‘days’ => int 737
This can be extremely useful in determining the time difference between two objects.
DateTime::getTimestamp() and DateTime::setTimestamp()
Sometimes it’s just useful to be able to grab the Unix timestamp from the DateTime object. But prior to PHP 5.3, to do so required some clunky code using strtotime() and a formatted date string. PHP has fixed this, and you can now use these getter and setter methods to get the Unix timestamp.
Write better object oriented PHP today.
Object oriented programming always leaves you with a headache. What if you could master it instead?Get the book now! »