Formatting 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);
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);
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);
Thursday December 20th, 2007
PHP code to show the RFC 2822 formatted date:
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.
- Convert a UNIX timestamp to a datetime with MySQL (Wednesday, January 13th 2010)
- Get the number of days in a month with PHP (Thursday, August 27th 2009)
- PHP's getdate() function (Monday, April 20th 2009)
- PHP Date Constants (Saturday, August 16th 2008)
- Using strtotime with PHP (Friday, December 21st 2007)