Skip to content

PHP DateTime and DateTimeZone Tutorial

With each new version PHP is getting more and more object oriented. In version 5.x we get two useful classes for date and time handling. Many programmers are still using outdated methods which are available in PHP mainly for compatibility reasons, so i want to introduce you to DateTime and DateTimeZone objects.

Server default Timezone

Before i do that, first let’s start with some basics, which tend to cause a lot of troubles in the beginning. Each computer has it’s own default timezone and local time set. If you are using Microsoft Windows, then probably timezone on your local machine is already set correctly, on the other hand if you are using Linux chances are that you will have to do it manually (i had to, however i am not using typical Linux so maybe this is just me).

PHP default Timezone

More over PHP has also it’s own default timezone, but doesn’t have it’s own time, which would be completely redicolous anyway. Obviously default PHP timezone can be found and changed in php.ini file, look for similar lines:

; Defines the default timezone used by the date functions
date.timezone = 'Europe/Warsaw'

I set date.timezone to Europe/Warsaw because it is my timezone, besides i have the same timezone set on my local machine. If you also changed these setting remember to restart your server before procceding.

Ok, enough with theory, when you run your scripts you can check and change your script timezone anytime you want. What does “script timezone” mean? Simply, that, despite you overwrite value from php.ini settings, this change is visible only in script which made this change.

It may sound complicated, but it is not and everything is done with only two functions, date_default_timezone_get() – which reads default timezone used in script, date_default_timezone_set() – sets default script timezone:

echo date_default_timezone_get();
echo date('H:i:s');
echo date_default_timezone_get();
echo date('H:i:s');

This script in my case outputs:


To be honest i have no idea why my default timezone is Europe/Berlin while i set it to Europe/Warsaw, more over phpinfo() says that my timezone is Europe/Warsaw, however there is no time difference between Berlin and Warsaw so everything is somewhat ok. Notice that when we changed default timezone, date or rather time has changed also.

DateTime and DateTimeZone

It often happens (or it just happened lately to me) that we want to know what is the time in different part of the world, this can be easily done using mentioned earlier DateTime and DateTimeZone classes.

$dateTime = new DateTime("now", new DateTimeZone('Europe/Warsaw'));
echo $dateTime->format("Y-m-d H:i:s");
$dateTimeZone = new DateTimeZone('GMT');
echo $dateTime->format("Y-m-d H:i:s");

The Output:

2008-06-02 21:32:46
2008-06-02 19:32:46

I know it’s a bit late, but i will finish this post anyway :). In the first line we create an instance of DateTime class, first argument passed to the constructor is time, i passed “now” which has the same meaning as NOW() in SQL. Second argument has to be instance of DateTimeZone class. You can also do not pass any arguments at all, then defaults will be used.

Take a look at fourth line, we simply change $dateTime timezone with DateTime::setTimezone() and voila, conversion from one timezone to another is done. As you can see conversion between two different timezones is very easy with these two classes.

Calculating difference between two dates

Did you ever wanted to calculated difference in days between two dates? Without DateTime class it could be quite diffycult, but isn;t anymore:

function dateDiff($dt1, $dt2, $timeZone = 'GMT')
    $tZone = new DateTimeZone($timeZone);
    $dt1 = new DateTime($dt1, $tZone);
    $dt2 = new DateTime($dt2, $tZone);
    $ts1 = $dt1->format('Y-m-d');
    $ts2 = $dt2->format('Y-m-d');
    $diff = abs(strtotime($ts1)-strtotime($ts2));
    $diff/= 3600*24;
    return $diff;
echo dateDiff('2008-01-05', '2008-05-20');

The only new (but not quit new in PHP) function here is strtotime() which parses date wrote as as string to UNIX timestamp. After substracting two timestamps, $diff is equal to number of seconds between these two days, we wanted to have difference in days, so we need to make additional arithmetic operations and return result. The most important here is use of the same timezone, if you forget about it then number of days may not be integer but real.

Other usage

I think you have to agree that DateTime and DateTimeZone classes are very useful however it is a schame that programmers didn’t thaught it would be handy to add __toString() method to both of this classes, but we are programmers as well so there is no problem in exending base classes:

class DTime extends DateTime
    public static $Format = 'Y-m-d H:i;s';
    public function __construct($date = null, DateTimeZone $dtz = null)
        if($dtz === null)
            $dtz = new DateTimeZone(date_default_timezone_get());
        parent::__construct($date, $dtz);
    public function __toString()
        return (string)parent::format(self::$Format);
$dTime = new DTime();
echo $dTime;

Outputs: 2008-06-02 19:32-46

Last thing i want to talk about is modyfing timestamp:

$date = new DateTime("2006-12-12");
$date->modify("+1 day");
echo $date->format("Y-m-d"); // 2006-12-13

This example was taken directly from PHP documentation, when you check date_modify() documentation you will find many more examples there, i won’t list them here becuase it simply doesn’t make any sense.

Published inMust Reads