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.

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

Hi! I'm Mike Dalisay, the co-founder of codeofaninja.com, a site that helps you build web applications with PHP and JavaScript. Need support? Comment below or contact [email protected]

I'm also passionate about technology and enjoy sharing my experience and learnings online. Connect with me on LinkedIn, Twitter, Facebook, and Instagram.