PHP Date and Time
The date function is used to format the date and time.
When setting the date and time, you first need to set the time zone.
date_default_timezone_set(‘UTC’);
Syntax
date(string format, int timestamp);
The first argument is required, the second is optional. If you do not specify the timestamp, the default value is the current time.
Date & Time
The following examples print out the date and time in various ways, as there are many ways to format date and time.
Example 1
The following example outputs the date and time.
echo date(“d-F-Y – h:i:s”);
Output
Example 2
The following example prints out the date, day, month and year, followed by the time in 12 hour format.
echo date("l-d-F-Y – h:i:s");
Output
Date
Now we will return only the date.
Example 1
echo date("D d M Y");
Output
Example 2
In this example we will add one day to the current day.
echo date("D d M Y" , strtotime('+1 day'));
This adds one day to the current day. You can do the same for year and month; simply change ‘day’ to ‘year’ or ‘month’.
Time
Now we will return only the time.
Example 1
echo date("h:i:s A");
The A at the end outputs ante meridiem and post meridiem (AM/PM); a capital ‘A’ will force it to be upper case while a lower case ‘a’ will force it to appear lower case.
Output
Example 2
This time we will add an hour to the current time.
echo date("h:i:s", strtotime("+1 hour"));
Output
You can also add minutes and seconds by simply changing ‘hour’ to ‘minute’ or ‘second’.
This table shows the various ways you can format the date and time:
Format Letter | Description |
---|---|
d | Day of the month as an integer |
m | Month as an integer |
y | Year but only the last 2 digits |
D | First 3 characters of the day, e.g. Sat |
M | First 3 characters of the month, e.g Jul |
Y | The year in full |
l | The day in full, e.g. Saturday |
h | Hours |
i | Minutes |
s | Seconds |
H | Time in 24 hour clock |
For a full list, see the PHP manual:
http://ca.php.net/manual/en/function.date.php
The time zone supports other values other than UTC; please see this manual:
http://ca.php.net/manual/en/timezones.php
Summary
This tutorial covered the basics of the date function in PHP. It is relatively simple to learn, and you can format the date and time in many ways.