📖 PHP Working with Dates

Dates and time are important aspects of human life. Incorporating dates and times into your web site improves its functionality for your users. Using dates and times in PHP can be frustrating to understand. Let's take a look at the common date and time methods in PHP.

PHP time uses a Unix timestamp. From Wikipedia: "Unix time is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, minus leap seconds; the Unix epoch is 00:00:00 UTC on 1 January 1970." It is important to understand this concept as the timestamp is central to the PHP time and date functions.

There are a few good resources to help you understand the PHP date functions.

time()

Returns the current time (timestamp) measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

date()

The date() function formats a local date/time. The format for this function is date(format, timestamp); where timestamp is an optional date. If omitted, the current [server] date and time will be used.

d - The day of the month (from 01 to 31)

D - A textual representation of a day (three letters)

j - The day of the month without leading zeros (1 to 31)

l (lowercase 'L') - A full textual representation of a day

S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j)

w - A numeric representation of the day (0 for Sunday through 6 for Saturday)

z - The day of the year (from 0 through 365)

F - A full textual representation of a month (January through December)

m - A numeric representation of a month (from 01 to 12)

M - A short textual representation of a month (three letters)

n - A numeric representation of a month, without leading zeros (1 to 12)

t - The number of days in the given month

L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)

Y - A four digit representation of a year

y - A two digit representation of a year

a - Lowercase am or pm

A - Uppercase AM or PM

g - 12-hour format of an hour (1 to 12)

G - 24-hour format of an hour (0 to 23)

h - 12-hour format of an hour (01 to 12)

H - 24-hour format of an hour (00 to 23)

i - Minutes with leading zeros (00 to 59)

s - Seconds, with leading zeros (00 to 59)

e - The timezone identifier (Examples: UTC, Atlantic/Azores)

Example
echo date("l");
// returns the day of the week like 'Tuesday'

echo date("l dS \of F Y h:i:s A");
// returns a formatted date string like 'Tuesday 24th of January 2006 02:41:22 PM'
mktime()

Since PHP uses Unix timestamps, you can use the mktime(); function below to convert a date to a Unix timestamp. The mktime(); function returns the Unix timestamp for a date. The format for mktime() is mktime(hour,minute,second,month,day,year,is_dst);

Date and Time Format
ParameterDescription
hour Optional. Specifies the hour
minute Optional. Specifies the minute
second Optional. Specifies the second
month Optional. Specifies the month
day Optional. Specifies the day
year Optional. Specifies the year
is_dst Optional. Set this parameter to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default) if it is unknown. If it's unknown, PHP tries to find out itself (which may cause unexpected results). Note: This parameter became deprecated in PHP 5.1.0. The new timezone handling features should be used instead
Example
echo date("l", mktime(0,0,0,10,3,1975));
// using mktime() to specify a date to the date() function
// returns 'Friday'
strtotime()

Another convenient way to retrieve a timestamp from a date is to use the strtotime() function to convert a human-readable time (12 hour clock) into a timestamp. This function helps to handle the AM/PM of a time by converting to a timestamp. The results can be used with other functions to return formatted strings.

$selectedTime = strtotime("$hours:$minutes:00 $ampm"); //convert selected 12 hour time to timestamp
$selectedTime = date("H:i:s", $selectedTime); //convert selected timestamp to 24 hour time
date_create()

Similar to mktime(), this function can create a DateTime object from a given date and time where the parts are combined (human readable). This is helpful when processing form data.

$selectedTimestamp = date_create("$year-$month-$day $selectedTime");
$timestamp =  date_timestamp_get($selectedTimestamp);
getdate()

The getdate() function returns an array of values for a date and time.

Format
$dateArray = getdate(timestamp);
// where timestamp is an optional date. If omitted, the current date and time will be used.

$dateArray = getdate(mktime(0,0,0,10,3,1975));
echo $dateArray['weekday'];
// returns 'Friday'

The $dateArray produced by the getdate() function above is an associative array with the following contents.

Key elements of the returned associative array
KeyDescriptionExample returned values
seconds Numeric representation of seconds 0 to 59
minutes Numeric representation of minutes 0 to 59
hours Numeric representation of hours 0 to 23
mday Numeric representation of the day of the month 1 to 31
wday Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
mon Numeric representation of a month 1 through 12
year A full numeric representation of a year, 4 digits Examples: 1999 or 2003
yday Numeric representation of the day of the year 0 through 365
weekday A full textual representation of the day of the week Sunday through Saturday
month A full textual representation of a month, such as January or March January through December
strtotime()

The strtotime(dateString, now) function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp relative to the timestamp given in now or the current time if now is not supplied.

Example
// use strtotime() to reformat a commonly written date
$day = strtotime("10:30 pm April 15, 2014");
echo "Created date is " . date("m/d/Y h:i:sA", $day) . "<br>\n";

// find the date for tomorrow
$day = strtotime("tomorrow");

// for next Saturday
$day = strtotime("next Saturday");

// for a date in the future
$day = strtotime("+3 Months");

// find the date 3 days from a given date
$startdate = strtotime("December 25");
$enddate = strtotime("+6 days", $startdate);
echo $enddate . "
\n"; echo "Six days after Christmas is " . date("l, F dS, Y", $enddate) . "<br>\n"; // find the number of days between dates $holiday = date('z', strtotime("July 04")); $today = date('z'); if ( $holiday == $today ) { // holiday is today echo "Happy holiday!"; } elseif( $holiday > $today ) { // holiday is after today $diff = $holiday - $today; echo "There are " . $diff . " days until holiday."; } else { // holiday is before today $endOfYear = date('z', strtotime("December 31")); $nextYear = date('z', strtotime("July 04 +1 year")); $diff = ( $endOfYear - $today ) + $nextYear; echo "There are " . $diff . " days until next year's holiday."; }
Timezones

PHP time is based on GMT at 0 degrees latitude. All other timezones are designated with positive and negative numbers. To make sure your visitors are seeing the time from the appropriate timezone, you may need to specify the timezone in your script. Use the date_default_timezone_set('timezone'); from the available timezone list to specify the timezone to be used by your script. You can also edit the php.ini file to set the default timezone if you have access to it. Usually, it is set by the server administrator to the local timezone of the server.

Example
date_default_timezone_set('America/Chicago');
// set the timezone using one of the available specified timezones
echo 'date_default_timezone_set: ' . date_default_timezone_get();
// use to check the timzone set with your script