How to Format Date Fetched From MySQL in PHP?

There are a lot of functions in PHP for dealing with date, time or timestamp. For a Beginner it might be trouble to choose the rights ones, although it’s really easy. In this post, I will especially Deal with the situation, where you fetched a Date from MySQL/PostgreSQL table, and you need to display it in a separate format.

What Function will we use?

Don’t Worry. I know you have tried using that but did not achieve the desired result. For those who haven’t tried, let me explain a little about the date() function. It accepts 2 Parameters. The first one is the format in which the date specified by the second parameter should be displayed.

MySQL Dates are in YYYY-MM-DD, this isn’t really the most universally accepted date format. Secondly, it isn’t really user Friendly. A user friendly Date Format would be 10 July 2013.

If you simply pass the MySQL date string to the date function, you will get an error. We need to convert the date into an UNIX timestamp format. To do that, we have to use the strtotime() function, which will convert any given date or time into a UNIX timestamp.

Following code demonstrates how to use the two functions together.

{code type=PHP}

//Fetch the reqd data from your table.
//Store your date in a variable called $sqldate

$date = strtotime($sqldate);

echo date(“j F Y”, $date); //output will be 10 July 2013

That’s all you need to do. There are plenty of options which will help you format the date in variety of ways. Read the Official Documentation about this function for more help and details.

6 thoughts on “How to Format Date Fetched From MySQL in PHP?

  1. Thanks for that. Might be worth changing the smart quotes on echo date(“j F Y”, $date); for normal “” ones.

Leave a Reply

Your email address will not be published. Required fields are marked *