Date and Time in PHP

PHP

If you need to work with date and time in PHP, you can use the date() function. It will output the date as well as time in your desired format. There are several formatting options. You can choose among them to decide how the date is displayed.

A simple example use of date() function is:

<?php
echo date("d M y");
?>
Output:
26 Oct 14

Here are a few formatting options for date in PHP

For Day of the Month:
d: Days like 01, 02, …, 30, 31 (Single digit is preceded by a 0)
j: Days like 1, 2, …, 30, 31 (Single digit does not have a zero in front)
S: Suffix for day. Like for 1 we use st to make it 1st and for 20 we use th to make it 20th. Works as st, nd, rd or th.

For Day of the Week:
D: Outputs the day of the week in short like Sun, Mon, …, Sat.
l: Outputs the full day of the week like Sunday, Monday, …, Saturday.

For Months:
F: Works for full month name like January, February, …, December.
M: Works for short month name like Jan, Feb, …, Dec.
m: Displays months as numbers like 01, 02, …, 12. (Single digit is preceded by a 0)
n: Displays month numbers like 1, 2, …, 12. (Single digit is not preceded by a 0)

For Year:
Y: Displays the full year like 2014.
y: Displays year number in two digits like 13, 14.

Time

The date() function itself is used to display time as well. Here are a few formatting options for time in php:

g: For hour in 12-hour format. 1, 2, …, 12.
h: For hour in 12-hour format with 0 preceding the single digits. 01, 02, …, 12.
G: For hour in 24-hour format. 1, 2, …, 24.
H: For hour in 24-hour format with 0 preceding the single digits. 01, 02, …, 24.
i: For minutes with 0 preceding the single digits. 01, 02, …, 60.
s: For seconds with 0 preceding the single digits. 01, 02, …, 60.

Now, let us take a look at these formatting options when used.

<?php
echo date('M dS y g:i:s'); //Output: Oct 26th 14 1:06:11
echo "<br />";
echo date('F dS Y h:i:s'); //Output: October 26th 2014 01:06:11
echo "<br />";
echo date('m/d/y'); //Output: 10/26/14
echo "<br />";
echo date('Y'); //Output: 2014
?>
Output:
Oct 26th 14 1:06:11
October 26th 2014 01:06:11
10/26/14
2014

Formatting the Unix Epoch date

Jan 1, 1970 in Unix time is 0 and the microseconds passed after this date is known as Epoch date. This date is used in programming. An example Unix Epoch time would be 1410004901.

To format it:

<?php
$epoch = 1410004901;
echo date('M d, y - g:i:s',$epoch);
?>
Output:
Sep 06, 14 - 7:01:41