Echo PHP Date From MySQL Output

When you store a date in MySQL it goes in as a not too friendly looking date and time and when you pull it back out again it’s going to need to be formatted. So what’s the deal? Well it depends on how you want to display that date on your pages but here’s where to start.

After you pull your rows ($row) out of the array of database entries you need to write

$the_date = date("d M Y", strtotime($row[0]));

echo $the_date;

where “d M Y” corresponds to the PHP date formatting you would like to display on your page. Similarly, $row[0], is relative to what place in the array the date exists. This example assumes it is the first place.

Basically the PHP strtotime() function does the work for you here and you don’t need to use stripslashes pulling the date from MySQL because it’s not user input. Hopefully that’s the simple answer you needed to know about outputting PHP dates from MySQL.

3 Responses to “Echo PHP Date From MySQL Output”

  1. Douglas Clifton Says:

    Assuming that you are talking about a basic date datatype in your MySQL table:

    1. That the year comes first in the output is an international standard.

    2. There is no need to use stripslashes() on any of the temporal types like you (may) need to worry about with character types.

    3. Let MySQL do the work for you, it’s much faster than calling 3 PHP functions for every row you select!

    mysql> select date_format(now(), ‘%m-%d-%Y’);


    See the MySQL Date and Time Functions for additional details.


  2. Douglas Clifton Says:

    Or, if you prefer the format like the one under message I just posted:

    mysql> select date_format(now(), ‘%d/%c/%Y @ %l:%i %p’);

    19/6/2005 @ 1:19 AM

  3. nortypig Says:

    Welcome to Pig Work. International date formats are even a bit geeky for me though - in normal suburban Tasmania I like day month year. But that one’s a choice.

    The mysql line is good advice. I’d been looking for it but like most cures to a problem I used the first that I actually found worked - thus the PHP one. Then I had to move on. But great now I have both Thanks :) I’ll put it into the SQL query as I get time. If I remember right I tried to get the SQL one working in my select first then went off and found the PHP cure.

    I’ve been an infrequent visitor on your blog in the past so it’s great hearing from you. While I’m a BComp student I’m far from a hard core programmer though. I think I’ll finish my degree and then try to follow a more graphic arts stream eventually.

    Its also good to have basic stuff like this around, there seems to be a lot of hardcore coding tutes out there but not enough low level stuff. Simple cures for everyday simple tasks… like this one. Hopefully someone who’s stuck might save half an hour by stumbling across it in Google. Maybe wishful thinking lol.

    Thanks again for commenting.