How to: Date Format

If you’re gonna display this date format in your page, it will look so elementary: 2010-10-20. So we got to have a format for this one.

How to: Date Format with PHP
Date Format

Step 1: Prepare your database configuration file.

Step 2: Create and put this code inside your index.php file.

include 'config_open_db.php';

// to format the date, we used the date_format function
// we also label the column as formatted_date 'coz if not, we will have to access the data
// in this way: date_format(date_created,'%M %d, %Y')
$sql = "select title, date_format(date_created,'%M %d, %Y') as formatted_date from articles";
$rs = mysql_query( $sql ) or die( 'Database Error: ' . mysql_error());
while( $row = mysql_fetch_array( $rs ) ){
extract( $row );
echo "<h4>$title</h4>";
echo "Created on " . $formatted_date. "< hr />";

you should have something like this:

Date Format

Step 3: If you also want to display the time just change %M %d, %Y to %M %d, %Y %r. You should have something like this.

Date Format With Time Specified

For more date format patter strings, look here.

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? You may use our comments section below or email our team at [email protected]

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top