Formatting Dates in PHP

Syntax:

1
2
$date = time();
$date_today = date("Y-m-d H:i:s", $date);

The time(); function will output the current date today in time stamp format.
The date(); function accepts two parameters, the first parameter is how you want to output the date and the 2nd parameter is the date to be formatted. If no parameters are provided, the default will be the value of the time(); function which is the current date.

List of Date Formats that you can use:

1
2
3
4
5
6
7
8
9
10
date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
date("m.d.y");                         // 03.10.01
date("j, n, Y");                       // 10, 3, 2001
date("Ymd");                           // 20010310
date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
date("H:i:s");                         // 17:16:18
date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)

To get the current date in an array format, use:

1
2
$today = getdate();
print_r($today);

The above code will output the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Array
(
    [seconds] => 5
    [minutes] => 50
    [hours] => 5
    [mday] => 3
    [wday] => 6
    [mon] => 5
    [year] => 2014
    [yday] => 122
    [weekday] => Saturday
    [month] => May
    [0] => 1399089005
)

To convert mysql date format (Ex. 2013-10-28 07:57:07) , we should first convert it using “strtotime”

1
2
3
$mysql_date = '2013-10-28 07:57:07';
$php_date = strtotime( $mysql_date );
$result = date( 'Y-m-d H:i:s', $php_date );

Reference: http://php.net/manual/en/function.date.php



Do you need help with a project? or have a new project in mind that you need help with?

Contact Me