PHP Web Development

Formatting dates in PHP

Formatting dates in PHP can seem a little daunting.  The best way to start is to ensure that you've stored all your dates with the slightly counter-intuitive time() function. This stores the date and time together in your database as one long number that really doesn't mean anything. This is a Unix timestamp.
The date() function is then used to reformat it. For instance 1206371089 comes out to March 24th, 2008 at 15:04:49 (GMT).

If your date/time is stored in the variable $lastupdated, you can display it in a friendlier format as;
[sourcecode language='php']
echo date("Y-m-d H:i:s",$lastupdated);

which will give you a date display like 2008-03-24 13:04:08 (note that this format is well suited to sorting chronologically in the output if it needs to be sorted after processing.)

If you need to refomat a date stored as a string, this is the way to do it;
[sourcecode language='php']
echo date("l jS F Y",strtotime("2008-03-05"));

You can format the dates pretty much however you want.  For a list of the format codes, it's best to go straight to the source at

Leave a Reply