PrimitiveType

Dates in PHP: Part 1

Dates are passed around a lot in web applications, so it's a good idea to be able to handle them properly. Thankfully, PHP provides many built-in functions to help with this. In this article, I look at how to display & format dates in PHP.

Very often, one my scripts will need to display a date in a certain format. I find that the best function for formatting dates is the date() function (see the date() PHP manual page). This function takes up to two parameters: a string, $format, and, optionally, an integer, $timestamp, which specifies what date to use. If you omit the $timestamp parameter, the current local date on the server is used.

As an example, the following code takes the current date and displays it in the format "1st of January 1970":

print date("jS \of F Y");

The format parameter is the string "jS of F Y", which contains characters which the function understands have special meanings. Stepping through that string, the function knows to replace "j" with the day of the month (with leading zeros), "S" with the ordinal suffix for the day of month (such as 1st), "F" with the full month name, and "Y" with the full, four digit year. Notice that the function did not convert "\of" into anything else. This is because the special character "o" was escaped using a backslash and the character "f" does not have a special meaning for the function. The manual page linked to above contains a table of the special characters accepted by the function.

The date function can also display information about the time of day. To print the time in the format "18:30:22" (hours:minutes:seconds) for a given timestamp, you would use:

print date("H:i:s", $timestamp);

The $timestamp parameter might be obtained or passed to you from another part of the application, but you can synthesize your own using the mktime() function.

As of version 5.1.1, PHP provides constants that can be used for the format parameter that will make your life a little easier. For example, the constant DATE_W3C can be used to format the date as such: 2007-03-01T17:52:01+00:00. Check these constants out at http://www.php.net/manual/en/ref.datetime.php#datetime.constants.

PHP provides an identical function, gmdate(), except that it returns a Greenwich Mean Time, as opposed to local, date/time. Another function, strftime(), can be used to format dates in a similar way to date(), but I find it slightly more awkward to use. However, it should be used to format dates in other languages.