PHP5 introduced a new function called date_format to format date and time into the string which was lacking in the earlier version of php. The function require two parameters: one is date object and second is format string.


string date_format ( DateTime $object, string $format )

Unfortunately, PHP4 and earlier version does not support date format function. We need to use date function to format and display date data. The older date function accept date timestamp integer instead of date object. we need to convert date object into timestamp using mktime function otherwise it will return default date 01-Jan-1970.


string date ( string $format [, int $timestamp] )

Convert date object into timestamp

We need to separate year, month, day, hour, min and sec form date object to pass into mktime function.

Use if mysql store date in YYYY-MM-DD HH:MM:SS format. If mysql uses YYYYMMDDHHMMSS format then you need to change number in the substr function to parse correct data.

$datetime = $row[‘date_added’]; //retrieve date from mysql database or use date() function to get current date and time

$year = substr($datetime,0,4);
$month = substr($datetime,5,2);
$day = substr($datetime,8,2);
$hour = substr($datetime,11,2);
$min = substr($datetime,14,2);
$sec = substr($datetime,17,2);

$tstamp = mktime($hour,$min,$sec,$month,$day,$year);
$tdate = date(“D M j G:i:s T Y”,$tstamp);

Date Format with preview

Format – h-i-s, j-m-y, it is w Day z
Preview – 05-16-17, 10-03-01, 1631 1618 6 Fri pm 01

Format – l dS \of F Y h:i:s A
Preview – Monday 15th of August 2005 03:12:46 PM

Format – F j, Y, g:i a
Preview – March 10, 2001, 5:16 pm

Format – H:m:s \m \i\s\ \m\o\n\t\h
Preview – 17:03:17 m is month

Format – l \\t\h\e jS
Preview – Wednesday the 15th

Format – \i\t \i\s \t\h\e jS \d\a\y.
Preview – It is the 10th day.

Format – D M j G:i:s T Y
Preview – Sat Mar 10 15:16:08 MST 2001

Format – j, n, Y
Preview – 10, 3, 2001

Format – Ymd
Preview – 20010310

Format – m.d.y
Preview – 03.10.01

Format – H:i:s
Preview – 17:16:17

Written by Bala Krishna

Bala Krishna is web developer and occasional blogger from Bhopal, MP, India. He like to share idea, issue he face while working with the code.