How to: Date Format

Photo of Mike Dalisay
Modified Monday, October 25, 2010
by - @ninjazhai
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.
For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.