Date and Time in 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:

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.

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:

You may also like

Comments are closed here.

Advertisements

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers