Cool DateTime Functions In PHP 5.3
January 25th, 2010 @ 1:00 amOver 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.
DateTime::diff()
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.
The original work of Brandon Savage.
Related posts:
Categories: Object-Oriented Development, PHP 5For some (perverse?) reason I feel I had to wrap Date around my own classes to utilise the new functionality… maybe I just favour my own API?
Another fine DateTime feature is native comparing:
<?php
$dateStart = new DateTime('yesterday');
$dateEnd = new DateTime('tomorrow');
if ($dateEnd
Hmm, using strip_tags() where you shouldn’t be using them?
Attempt two: http://pastebin.com/f62cdf95f
Yes, I started using DateTime recently because of its representation being better than using date strings, and it’s ability to represent a much larger date range than unix timestamps.
On the Zend Framework contributors mailing list, there’s a discussion at the moment of the possibility of scrapping Zend_Date or extending DateTime sometime in the future. Zend_Date uses mktime internally, so not as good.
Before PHP 5.3, you are able to run “$date->format(‘U’)” and “new DateTime(‘@’.$timestamp)”, rather than having to run the functions you mentioned.
Your diff example appears to be missing some code.
Thanks for the write up, was not away of this new object. Should make development that much better!
thanksa lot for this article, i didn’t know much about datetime object in php…
I like using this to display the run time of a script (especially those long ones that might take 30 minutes to run).
What’s great about using an object is that you have a lot of built in functionality that you would have to otherwise build in yourself.
I like the features, but the syntax just seems purposely odd.
PostgreSQL has supported this type of date/time transformations with some very straight forward syntax – http://www.postgresql.org/docs/8.4/interactive/functions-datetime.html
date(‘U’); // <— this works great if you want the current unix timestamp
Web developer, amateur photographer, lover of the outdoors and travel. Expect to find me writing code, hiking or visiting new places. I own Blueprint DC and live in Washington, DC. Follow Me On Twitter!- July Slides
- Some Thoughts On Software Licensing
- Interfaces Make Testing Easier
- Revisiting: Why Every Developer Should Write Their Own Framework
- The Fallacy of Sunk Cost
- PHP: The Good Parts – Book Review
- 1st Amendment, Meet 4th Amendment: The Gizmodo Search Warrant
- A Closer Look At ArrayObject
- TEK Webcast Notes
- Caching For WordPress – A TEK-X Webinar

Is there any code missing in second example ?
diff($dt2));
?>
I think there is some ;)