Make A Date With PHP's Powerful DateTime Functions

When working on PHP code that calls for date and time manipulation, especially forums, discussion boards and blogs where date and time functions are important, you’ll regularly encounter situations where you need to display different formats or styles of date and time.

PHP includes a range of functions which can help you to easily format and adjust your date and time displays to suit your needs. In this tutorial, we’ll look at some easy ways to display calendar information for your visitors.

time() or, the Unix Timestamp

One of the simplest date/time functions in PHP is time(). This simple function takes no arguments, and simply returns a numeric value equal to the number of seconds since the “Unix Epoch”, declared as January 1st 1970 at midnight (GMT) - just an arbitrary date chosen to base timing calculations on when working with dates and times. This gives a start time upon which we can base our time calculations

$time = time();
echo $time; //gives us something like 1219075172

PHP’s date() function

This timestamp can then be used as input to the date() function to format it for improved readability. The date() function takes, as its arguments, a string to define how we wish the formatted time to appear and secondly, a Unix timestamp just like the one returned by time(). It is also possible to use date() without specifying a timestamp and it will use the current time as its source.

echo date("F j, Y, g:i a", 1219075172); //produces "August 18, 2008, 4:59 pm"

The string used in the date() function can contain a number of single letters which are then substituted for their human readable counterparts according to the value of the timestamp. In our case, the following substitutions are made

  • F: The full textual representation of the month, August in this case
  • j: The day of the month, without leading zeros, e.g. 4, 18, 22
  • Y: The full year, e.g. 2008
  • g: The current hour, in 12-hour format
  • i: The current number of minutes
  • a: Either am, or pm, depending on the time A full list of all the codes, and their textual counterparts can be seen on PHP.net’s date() page here. Extra text can be added to the formatted string as required, but remember to escape any characters which date() will interpret as formatting text.

Make time with mktime()

An alternative to the time() function is mktime(). This function is useful when we wish to use a date/time which is not the current time. mktime() takes as its arguments numerical values representing, in this order - hours, minutes, seconds, months, days, years - and a final value to declare whether daylight savings time is to be taken into account.

$date = mktime(10, 15, 0, 12, 12, 1980); //produces 345464100
echo date("F j, Y, g:i a", $date); //produces "December 12, 1980, 10:15 am"

microtime()

The PHP function microtime() returns a similar value to time(), but returns a more accurate floating-point representation of the number of seconds since the Unix Epoch. It is not usually used in the same way as the previous time functions, but is used more often when debugging PHP code and analysing the time of execution of functions for performance enhancement purposes microtime() only takes one argument, and that is a boolean value stating whether or not to return the value as a floating point number rather than a formatted string. Using microtime() without this parameter can produce some confusing results if you’re not aware of its behaviour. Notice here how the first call returns the time as a string split into microseconds and seconds

echo microtime(); // produces 0.61273200 1219075923
echo microtime(true); // produces 1219075923.6128

If you try using the value of the first function call directly, PHP will treat it as a string, and give inaccurate results.

microtime() for debugging and code analysis

Here is an example of using microtime() to measure the performance of a for-loop compared with a while-loop performing 10 million repetitions of a single increment operation. Before each loop, we record the start time using microtime(), and compare it to the end time after each loop is complete.

$while_start = microtime(true);
$count = 0;
while($count < 10000000){
    $count++;
}

$duration_while = (microtime(true)-$while_start)*1000;
printf ("While loop execution in %.3f ms", $duration_while);

$for_start = microtime(true);

$count = 0;
for($i=0; $i<10000000; $i++){
    $count++;
}

$duration_for = (microtime(true)-$for_start)*1000;
printf ("For loop execution in %.3f ms", $duration_for);

This code produces the following result (based upon execution times on my system)

While loop execution in 787.590 ms
For loop execution in 1363.392 ms

We also multiply the values on lines 6 and 13 to get a value in microseconds, rather than seconds

strtotime(), String To Time

Sometimes you’ll find it useful to be able to tell a PHP in plain language exactly what time you want to send to the date() function. The strtotime() function can do just that. It will take as an input an English-language string describing a date and convert it into a Unix timestamp which can then be passed into the date() funtion. It will take an optional second value of another Unix timestamp from which to calculate the result. For example (this code was generated on Monday, 18th August, 2008)

echo date("jS F, Y", strtotime("next friday")); //22nd August, 2008
echo date("jS F, Y", strtotime("last tuesday")); //12th August, 2008
echo date("jS F, Y", strtotime("3 years, 2 months, 1 day"));  //19th October, 2011
echo date("jS F, Y", strtotime("5 weeks ago")); //14th July, 2008

The strtotime() function will pick up on most English language date descriptions you give it, but it’s not perfect! For a full description of the strings you can pass to it, check out the GNU Date input formats