Formatting Dates with PHPFormatting Dates with PHP

Posted December 20th, 2007 in PHP

PHP has a really useful date() function for formatting dates from timestamps. When used in conjunction with strtotime() you can do some really quick and easy manipulation and formatting of dates.

The PHP date() function works like this:

string date ( string $format [, int $timestamp ] )

You pass it a format string to specify what format you want the date in, and an optional timestamp as the date to format. If you don't specify the timestamp then the current timestamp is used. The timestamp is a UNIX timestamp, which is an integer value; eg December 20th at 2pm would be represented as 1198112400 as a UNIX timestamp.

Passing the above example timestamp (which is the publish date and time of this post) would yield the following examples:

PHP code to show the date in YYYY-MM-DD format (MySQL date format):

$ts = 1198112400;
echo date('Y-m-d', $ts);

Result:

2007-12-20

PHP code to show the date in YYYY-MM-DD HH:MM:SS format (MySQL datetime format):

echo date('Y-m-d H:i:s', $ts);

Result:

2007-12-20 14:00:00

PHP code to show the date of the week, month name, day of the month with ordinal suffix (ie st, nd, rd)) and year:

date('l F jS, Y', $ts);

Result:

Thursday December 20th, 2007

PHP code to show the RFC 2822 formatted date:

date('r', $ts);

Result:

Thu, 20 Dec 2007 14:00:00 +1300

A full list of formatting placeholders can be found in the PHP Manual.

Using strtotime to convert dates to timestamps

A date and time stamp retrieved from a database query is often in the format YYYY-MM-DD HH:MM:SS which is not the sort of timestamp that can be accepted by the date() function. If you pass a string value to date() as the timestamp then it will first convert it to an integer which will yield 0, and is the equivilent of January 1st 1970.

First you must convert the date time string value to an integer, which can easily be done using the strtotime() PHP function like so:

$ts = strtotime($string_datetime);
echo date($format, $ts);
// or
echo date($format, strtotime($string_datetime));

Tomorrow I'll look at strtotime() further, and the useful things that can be done with it.

Related posts:

Comments

blog comments powered by Disqus