Getting to grips with time in PHP

Working with time-sensitive code in PHP can get a little confusing (for me at least) when you have to deal with calculations in up to three different time zones: the server time zone, GMT or UTC, and the client time zone. Here's a little table with the most important time functions in PHP, that seeks to help clarify what they do.

The server time zone used for these examples is GMT+1. The Unix epoch is defined as Thu, 01 Jan 1970 00:00:00 GMT (and is therefore a fixed point in time, regardless of local time zone).

FunctionOutputComments
time()
(run on Tue, 01 Dec 2009 00:00:00, server time)
1259622000The number of seconds between the Unix epoch and the run-time of the function.
mktime(0,0,0,12,1,2009)1259622000The number of seconds between the Unix epoch and the input time (specified in the server time zone).
gmmktime(0,0,0,12,1,2009)1259625600The number of seconds between the Unix epoch and the input time (specified in GMT).
strtotime('Tue, 01 Dec 2009 00:00:00')1259622000Without a timezone specified in the input string, the function assumes it is in the server time zone.
strtotime('Tue, 01 Dec 2009 00:00:00 GMT')1259625600With a timezone specified in the input string, the function will use that time zone instead of the server time zone.
date('D, d M Y H:i:s', 1259622000)Tue, 01 Dec 2009 00:00:00Takes a Unix timestamp (by definition in GMT) and returns a formatted date in the server time zone.
gmdate('D, d M Y H:i:s', 1259622000)Mon, 30 Nov 2009 23:00:00Takes a Unix timestamp (by definition in GMT) and returns a formatted date in GMT.

The Unix timestamps used above translate to the following GMT times:

  • 1259622000: Mon, 30 Nov 2009 23:00:00 GMT
  • 1259625600: Tue, 01 Dec 2009 00:00:00 GMT

    When dealing with time-related calculations, I strongly recommend doing all the number-crunching in GMT, and translating this to client/server time afterwards, otherwise you seriously risk getting confused (especially if you have things like daylight savings to contend with as well).

    The date_default_timezone_set function can be used to specify your own time zone for PHP to use (overriding the server time zone) - I find it is easiest to set this to GMT, thereby eliminating the complexity introduced by the server time zone.

    PHP function references: time, mktime, gmmktime, strtotime, date, gmdate, date_default_timezone_set