Don't live in the past: use Datetime instead!

alt clock

When I search and read code about time and date problems, I noticed that a lot of people still use the old PHP functions like date(), time() or strtotime().

What about using Datetime instead?

It is time to introduce this powerful PHP object.

Datetime can do all the usual date and time operations you could ask for and even more. Using Datetime can save a lot of time when you have to do more complex operations on dates.

Now I see you asking: why using Datetime instead of a bunch of PHP date functions?

Here's why:

  • The object Datetime is definitely more robust to use. Less bug is always better.

  • Datetime is an object. You can use composition or inheritance to modify his behavior depending on your need.

  • Using one object is more clear for your fellow developer colleagues. Even if they don't know Datetime, they just have to look to the documentation for one single object. It is definitely better than looking for the documentations of three different functions!

Basics

The instantiation is easy: you can pass to the constructor a date correctly formatted or nothing if you want to manipulate the current date.

Here the list of supported date and time formats you can inject in the constructor.

You can then format the date in order to display it in two lines of code:

$dateTime = new DateTime('2016-01-01');
echo $dateTime->format('Y-m-d H:i:s');`  

Output: 2016-01-01 00:00:00

$dateTime = new DateTime();
echo $dateTime->format('Y-m-d H:i:s');`  

Output whatever the current date is, correctly formatted.

Easy, isn't it? You can as well, as a second argument, precise your timezone in the constructor as follow:

$date = new DateTime('2016-05-20', new DateTimeZone('Europe/Berlin'));

What about using a timestamp and then formatting it in a friendly date? Easy peasy!

$dateTime = new DateTime();
$dateTime->setTimestamp(1271802325);
echo $dateTime->format('Y-m-d H:i:s');  

Output: 2010-04-20 22:25:25

Obviously you can as well output a timestamp if you need to:

$dateTime = new DateTime('2016-05-20');
echo $dateTime->getTimestamp();  

Output: 1271802325

What about adding or retrieving a day, a minute, an hour of a date using this known formatting?

$dateTime = new DateTime('2016-01-01');
$dateTime->modify('+1 day');
echo $dateTime->format('Y-m-d H:i:s');`  

Output: 2016-01-02 00:00:00

You can as well use the constructor if you work on the current date:

$dateTime = new DateTime('+1d');
echo $dateTime->format('Y-m-d H:i:s');`  

Output the current date plus one day.

Comparisons

Datetime objects can as well be used to compare dates and it's where Datetime can be really, really handy.

We need to introduce a new object though, which complicate a bit the code but nothing really significant, specially if we try to achieve the same results without using those objects.

Here an example:

$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y-%m-%d %H:%i:%s');  

Output: 00-0-1 22:0:0

In this example we created two Datetime objects. They will receive two different dates in their constructors.

In order to compare those two dates we use the method diff() of the first Datetime object with the second Datetime object as argument.

The diff() method will return a new object of type DateInterval. If you want to format the difference between the two dates, you can use as well the format() method of the DateInterval object but be careful: it won't accept the same formatting as the Datetime::format() method.

You can see the format accepted by the DateInterval object here.

The output indicate that there is 1 day and 22 hours difference between the two dates.
If you only want the seconds, hours or day of interval you can write:

$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->s;  
echo $interval->h;  
echo $interval->d;

Output:

0  
22  
1  

Moreover if you need to compare quickly two date with the usual comparaison operators, you can simply do that:

$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');

if($datetime1 > $datetime2){  
    echo 'datetime1 greater than datetime2';
}
else{  
    echo 'datetime2 greater than datetime1';
}

Output: datetime2 greater than datetime1

Simple, elegant and powerful

I invite you to consult the PHP documentation about the Datetime object. As we just saw it is a must-know and powerful object.

If you know other situations where this object become handy, please don't hesitate and leave a comment!