PHP Date() Cheatsheat

Table of Contents

Basic usage

date(format string, [optional unix timestamp])

The timestamp must be specified as the number of seconds since 1970, a common internal date metric used by unix systems. To generate a timestamp for a specific date use mktime() or strtotime() -- see below. If this parameter is not specified, date() will use the current server time. gmdate() is identical to date() but will report the equivalent time in Greenwich Mean Time (GMT).

PHP has no built-in date variable type. The closest thing to it is a timestamp integer, or any string that strtotime() can parse into a timestamp integer.

Interactive

date('');
Result:

date() format string syntax

CharDescriptionExample returned values
Day
dDay of the month, 2 digits with leading zeros01 to 31
DA textual representation of a day, three lettersMon through Sun
jDay of the month without leading zeros1 to 31
lA full textual representation of the day of the weekSunday through Saturday
NISO-8601 numeric representation of the day of the week. See also w. (added in PHP 5.1.0)1 (for Monday) through 7 (for Sunday)
SEnglish ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
wNumeric representation of the day of the week0 (for Sunday) through 6 (for Saturday)
zThe day of the year (starting from 0)0 through 365
Week
WISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)Example: 42 (the 42nd week in the year)
Month
FA full textual representation of a month, such as January or MarchJanuary through December
mNumeric representation of a month, with leading zeros01 through 12
MA short textual representation of a month, three lettersJan through Dec
nNumeric representation of a month, without leading zeros1 through 12
tNumber of days in the given month28 through 31
Year
LWhether it's a leap year1 if it is a leap year, 0 otherwise.
oISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)Examples: 1999 or 2003
YA full numeric representation of a year, 4 digitsExamples: 1999 or 2003
yA two digit representation of a yearExamples: 99 or 03
Time
aLowercase Ante meridiem and Post meridiemam or pm
AUppercase Ante meridiem and Post meridiemAM or PM
BSwatch Internet time000 through 999
g12-hour format of an hour without leading zeros1 through 12
G24-hour format of an hour without leading zeros0 through 23
h12-hour format of an hour with leading zeros01 through 12
H24-hour format of an hour with leading zeros00 through 23
iMinutes with leading zeros00 to 59
sSeconds, with leading zeros00 through 59
uMilliseconds. See microtime() for the equivalent in earlier versions of PHP. (added in PHP 5.2.2)Example: 54321
Time zone
eTime zone identifier (added in PHP 5.1.0)Examples: UTC, GMT, Atlantic/Azores
IWhether or not the date is in daylight saving time1 if Daylight Saving Time, 0 otherwise.
ODifference to Greenwich time (GMT) in hoursExample: +0200
PDifference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3)Example: +02:00
TTime zone abbreviationExamples: EST, MDT ...
ZTime zone offset in seconds. The offset for time zones west of UTC is always negative, and for those east of UTC is always positive.-43200 through 50400
Full Date/Time
cISO 8601 date. Equivalent to Y-m-d\TH:i:sO. (added in PHP 5)Example: 2007-02-12T15:19:21+00:00
rRFC 2822 formatted date. Equivalent to D, d M Y H:i:s O.Example: Thu, 21 Dec 2000 16:01:07 +0200
USeconds since the Unix Epoch (January 1 1970 00:00:00 GMT)Equivalent to calling time().
Misc
\Backslash metacharacter. Use to escape a character to be taken as a literal. Remember to use single quotes when escaping to prevent characters like \n or \r from becoming newlines, etc.\Y Y results in Y 2007

(Adapted from the PHP manual, copyright © 1997 - 2007 the PHP Documentation Group)

Common formats

MySQL date format:

date('Y-m-d H:i:s')

- or, for date only: -

date('Y-m-d')

This is the format to use in MySQL SQL statements to express dates in string form.

The documentation does not specify a way to indicate a time zone; the date should be in the time zone that the MySQL server is set to use in order to be correct. If PHP and MySQL are on the same server then date() should normally already express dates using the same time zone as MySQL. For more about time zone issues with PHP and MySQL, see this article.

Context example: INSERT INTO purchase (prodcode, quantity, thetime) VALUES ('toytruck', 1, '2004-04-16 13:24:07');

Reference

HTTP header date format:

gmdate('D, d M Y H:i:s \G\M\T')

This is the format to use for HTTP headers such as Date:, Expires: and Last-Modified:, but not the Set-Cookie:, header which uses a different format, shown in the next section.

Note that this uses the gmdate() function, which is identical to date() except it converts the date to the GMT time zone; also, PHP may report GMT as 'UTC', however the standard requires that UTC always be represented as 'GMT'.

Context example:

HTTP/1.1 200 OK
Date: Mon, 19 Nov 2007 23:47:33 GMT
Server: Apache/1.3.33 (Darwin) PHP/4.4.7
Last-Modified: Mon, 19 Nov 2007 23:40:02 GMT
Accept-Ranges: bytes
...

Reference

HTTP cookie date format:

gmdate('D, d-M-Y H:i:s \G\M\T')

This format is for the expiration date of HTTP cookies, and is equivalent to the toGMTString() method of date objects in javascript. Note that this also uses gmdate() and forces 'GMT' instead of 'UTC' as the reported time zone, as required by the specification.

Context example: Set-Cookie: RMID=732423sdfs73242; expires=Fri, 31-Dec-2010 23:59:59 GMT; path=/; domain=.example.net

Reference

RSS date format:

date('D, d M Y H:i:s T')

- or -

date('D, d M Y H:i:s O')

This date format is used in RSS feeds, in XML elements such as pubDate or lastBuildDate. The date format must be RFC 822 compliant but a 4 digit year is preferred. Unlike the format used by HTTP headers, GMT is not required, and the time zone may be expressed using the either time zone abbreviation ('T') or the offset from GMT ('O').

Context example:

<rss version="2.0">
<channel>
<title>Apple Hot News</title>
<link>http://www.apple.com/hotnews/</link>
<description>Hot News provided by Apple.</description>
<language>en-us</language>
<copyright>Copyright 2007, Apple Inc.</copyright>
<pubDate>Fri, 16 Nov 2007 14:47:14 PST</pubDate>
<lastBuildDate>Fri, 16 Nov 2007 14:47:14 PST</lastBuildDate>
...

Reference 1 Reference 2

Atom date format:

date('c') (PHP 5)

- or -

gmdate('Y-m-d\TH:i:s\Z')

Dates in atom files must be compliant with RFC 3339. GMT/UTC is not required.

For versions of PHP earlier than 5.0 and therefore lacking the handy 'c' specifier for ISO 8601 dates, of which RFC 3339 is a subset, getting the time zone specified correctly was tricky for non-GMT dates. Forcing GMT and denoting it as 'Z' will work in all PHP versions.

Context example:

<feed xmlns="http://purl.org/atom/ns#draft-ietf-atompub-format-08">
<title>Example Feed</title>
<link href="http://example.org/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author> <name>John Doe</name> </author>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://example.org/2003/12/13/atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
...

Reference

Unix/C date format:

date('D M j G:i:s T Y')

This is the date format as reported by unix utilities such as date and not coincidentally the format used by ANSI C's asctime() function. The equivalent in the format used by the date utility, as well as the C and alias PHP function strftime(): '%a %b %e %H:%M:%S %Z %Y'.

Example: Mon Nov 19 19:03:52 EST 2007

Reference

mktime() and strtotime()

In order to generate dates for times other than the current time, you will need to use mktime() and strtotime(). mktime() takes a series of integers as inputs, while strtotime() parses many human-readable string date formats and may be more convenient to use. Both functions can also be used to manipulate relative dates (e.g. date('Y-m-d', strtotime('tomorrow')).

mktime()

mktime ( [hour [, minute [, second [, month [, day [, year [, daylight savings: 0 for no dst; 1 for dst; -1 dst unknown]]]]]]] )

Examples:

$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);

Note that these examples will handle daylight savings appropriately as well as overflows, e.g. November 32 will be interpreted as December 1. This may be useful for doing date math. The DST argument is now deprecated and should be left at the default value of -1, according to which DST will be automatically detected and handled.

(Examples from the PHP manual)

strtotime()

strtotime('');
Result:

PHP's extremely convenient strtotime() function is adapted from the get_date GNU library. It can convert myriad textual human representations of dates/times into Unix timestamps.

This can be very useful when converting between any of the common date formats above, especially when encountering non- standards-compliant data.

Some examples:

strtotime('2003-07-30 -1 month');
strtotime('1972-09-24');
strtotime('72-9-24');
strtotime('72-09-24');
strtotime('24 September 1972');
strtotime('24 Sept 72');
strtotime('24 Sep 72');
strtotime('Sep 24, 1972');
strtotime('24-sep-72');
strtotime('24sep72');
strtotime('24-sep-72 20:02');
strtotime('24-sep-72 8:02pm');
strtotime('1 year');
strtotime('1 year ago');
strtotime('3 years');
strtotime('2 days');
strtotime('-1 month');
strtotime('now');
strtotime('+1 week');
strtotime("+1 week 3 days 2 hours 8 seconds");
strtotime('next Thursday');
strtotime('last Monday');

Some units of time that strtotime() understands:

Some relative and ordinal words that strtotime() understands:

Usage tips:

(Some examples in this section borrowed from the GNU tar manual, copyright © 2004 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.; word specifier lists adapted from PHP Functions Essential Reference, copyright © 2002 New Riders Publishing.)

Common problems

While PHP has some very powerful date functions, because of the lack of a date type often date math can be counterintuitive. Here are some common general problems and how to solve them.

For more robust solutions, consider using one of the date objects such as PEAR Date listed below.

Getting the difference between two dates

There is no terribly intuitive way to do date math in PHP using only the built-in functions.

Because PHP has no built-in date type — the closest thing to it is the timestamp integer returned by time() and mktime() — calculating the differences between dates can be a little tricky. Generally solutions will use strtotime() and/or mktime().

There are a large number of user-defined functions floating around that attempt to solve this problem. One such function recently seen in comments on the PHP manual:

	function date_diff($d1, $d2){
		$d1 = (is_string($d1) ? strtotime($d1) : $d1);
		$d2 = (is_string($d2) ? strtotime($d2) : $d2);

		$diff_secs = abs($d1 - $d2);
		$base_year = min(date("Y", $d1), date("Y", $d2));

		$diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
		return array(
			"years" => date("Y", $diff) - $base_year,
			"months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
			"months" => date("n", $diff) - 1,
			"days_total" => floor($diff_secs / (3600 * 24)),
			"days" => date("j", $diff) - 1,
			"hours_total" => floor($diff_secs / 3600),
			"hours" => date("G", $diff),
			"minutes_total" => floor($diff_secs / 60),
			"minutes" => (int) date("i", $diff),
			"seconds_total" => $diff_secs,
			"seconds" => (int) date("s", $diff)
		);
	}
	

This function can take either timestamps as input or strings containing any value that strtotime() can understand.

link

Adding to or subtracting from a date

Perhaps the simplest way to add to or subtract from a date is to use strtotime().

Create the date value as a string (possibly using date() if the date you're working with is already a timestamp) and then add or subtract with a + or - sign followed by amount of time in any unit that strtotime() understands (see above).

Examples:

strtotime('now + 7 days')

strtotime('10/27/2007 8:15 pm - 900 seconds');

 

As an alternative, mktime() correctly handles overflows, such that inputting a date for the 32nd day of December will correctly return a timestamp equivalent to January 1st of the following year.

Example:

mktime(0, 0, 0, 12, 32, 1999)

However, strottime() can handle more complex units of time such as weeks or days of the week, which mktime() cannot.

Comparing dates

The simplest, most intuitive way to compare dates is to use strtotime().

To find out a given date is more or less than weeks from the current time, use this:

strtotime('2007-10-31 12:00:00') > strtotime('2 weeks ago');

Other resources

$LastChangedDate: 2008-04-20 22:07:55 -0400 (Sun, 20 Apr 2008) $