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. Date Format Step 1: Prepare...

Mike Dalisay

Mike Dalisay

Updated on October 25, 2010

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.

<?php
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.

PHP Tutorial Series

Explore the tutorials that have been most helpful to our community of coders.