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.

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:

object(DateInterval)[3]

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.

Frustrated with your company’s development practices? You don't have to be! No matter what the issues are, they can be fixed. You can begin to shed light on these issues with my handy checklist. Plus, I'll help you with strategies to approach the issues at the organization level and "punch above your weight."

Great! We'll be updating you soon on best practices for your team!

Brandon Savage is the author of Mastering Object Oriented PHP and Practical Design Patterns in PHP