May 072012
 

If you save your date in the format of timestamp in your MySQL database, and want to output it like this:

$result = mysql_query("SELECT * FROM articles");
$row = mysql_fetch_array($result);
$date = $row['timestamp'];
echo $date;

Your date come out looking something like this: 2011-01-30 20:54:12
So it’s formated like YYYY-MM-DD HH:MM:SS

But what if you want it to display, say like this: Sunday, January 30th, 8:54pm
Normally you would use the date function and pass it a format string and a timestamp. Like this:

$result = mysql_query("SELECT * FROM articles");
$row = mysql_fetch_array($result);
$date = $row['timestamp'];
echo date("l, F jS, g:ia", $date);

But that will give you an error, since the second argument of the date function expects a UNIX timestamp (which is the number of seconds passed since 1970-01-01 00:00:00 until a given date).

In our example the variable $date holds a string that looks like this ‘2011-01-30 20:54:12‘. The date function doesn’t know what to do with that information. So we need to convert the date string to a UNIX timestamp.

Luckily there’s a function called strtotime(), that will take care of this for us.

$result = mysql_query("SELECT * FROM articles");
$row = mysql_fetch_array($result);
$date = $row['timestamp'];
$date = strtotime($date);
echo date("l, F jS, g:ia", $date);

After running the $date variable through the strtotime function (on line 4) it will hold the value 1296420852. The date function will now return the date of this timestamp – in the format we passed in the first argument.

Check out the date function on php.net to learn more about how to format the date string.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>