Date and Time Function in PHP

PHP date() Function

PHP date function is an in-built function that simplify working with date data types. The PHP date function is used to format a date or time into a human readable format.

It can be used to display the date of article was published. Record the last updated a data in a database.

Dates are so much part of everyday life that it becomes easy to work with them without thinking. PHP also provides powerful tools for date arithmetic that make manipulating dates easy.

PHP Date Syntax and Example

PHP Date the following basic syntax

<?php
	date(format, [timestamp]);
?>
  • date() is the function that returns the current timestamp in PHP on the server.
  • format is the general format which we want our output to be.
  • Y-m-d for PHP date format YYYY-MM-DD.
  • Y to display the current year.
  • [timestamp] is optional. If no timestamp has been provided, PHP will get the current PHP date time on the server.

Let’s look at a basic example that displays the current year.

<?php
	echo date("Y");
?>

Output: 2024


Getting the Time Stamp with time()

PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.

The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.

<?php
	print time();
?>

This will produce the following result:

1480930103

This is something difficult to understand. But PHP offers excellent tools to convert a time stamp into a form that humans are comfortable with.


Converting a Time Stamp with getdate()

The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().

Following table lists the elements contained in the array returned by getdate().

KeyDescriptionExample
secondsSeconds past the minutes (0-59)20
minutesMinutes past the hour (0 - 59)29
hoursHours of the day (0 - 23)22
mdayDay of the month (1 - 31)11
wdayDay of the week (0 - 6)4
monMonth of the year (1 - 12)7
yearYear (4 digits)2024
ydayDay of year ( 0 - 365 )19
weekdayDay of the weekSunday
monthMonth of the yearAugust
0Timestamp948370048

Now you have complete control over date and time. You can format this date and time in whatever format you wan.

Example:

<?php
	$date_array = getdate();
	foreach ( $date_array as $key => $val ){
		print "$key = $val<br />";
	}
	$formated_date = "Today's date: ";
	$formated_date .= $date_array['mday'] . "/";
	$formated_date .= $date_array['mon'] . "/";
	$formated_date .= $date_array['year'];
	print $formated_date;
?>

This will produce following result:

seconds = 10
minutes = 29
hours = 9
mday = 5
wday = 1
mon = 12
year = 2016
yday = 339
weekday = Monday
month = December
0 = 1480930150
Today's date: 5/12/2016

Date and Time Functions

checkdate(): Validates set of Gregorian year, month, and day values (for example, 2005, 3, 17).

date_sunrise(): Returns time of sunrise for a given day and location (new in PHP 5).

date_sunset(): Returns time of sunset for a given day and location (new in PHP 5).

date(): Formats a local date/time, given a Unix timestamp (for example, 1111035030000 ) and a formatting string.

getdate(): Given a Unix timestamp, returns an associative array containing date and time information (defaults to current time).

gettimeofday(): Returns an associative array containing information about the current system time.

gmdate(): Formats a GMT/UTC date/time. Uses the same formatting characters as the date() function.

gmmktime(): Converts a set of GMT date/time values into a Unix timestamp (analogous to mktime()).

gmstrftime(): Formats a GMT/UTC date/time according to locale settings idate() Formats a local time/date value as an integer.

localtime(): Given a Unix timestamp, returns an array of date/time values.

microtime(): Returns a string representation of the current Unix timestamp with microseconds.

mktime(): Converts a set of local date/time values into a Unix timestamp.

strftime(): Given a timestamp and a formatting string, returns a representation of a local date/time according to locale settings.

strptime(): Given a date/time string generated with strftime() and the formatting string used to generate it, returns a Unix timestamp (new in PHP 5.1).

strtotime(): Converts an English textual date/time description into a Unix timestamp.

time(): Returns the current system date and time as a Unix timestamp.


Formatting Characters for the date() Function

Month Parameters

CharacterDescription
FFull name of the month (January, February, and so on).
MThree-letter abbreviation for the month (Jan, Feb, and so on).
mNumeric representation for the month, with leading zero (two digits).
nNumeric representation for the month (no leading zero).
tReturns the number of days in a month [28 to 31]

Day Parameters

CharacterDescription
dDay of the month, with leading zeros (two digits).
jDay of the month (no leading zeros).
sOrdinal suffix for the day of the month, two characters (st, nd, th); most commonly used in combination with j.
lFull name of the day of the week (Monday, Tuesday, and so on).
DA textual representation of a day, three letters (Mon, Tue, and so on).
wNumeric representation of the day of the week (0 = Sunday, 6 = Saturday).
zReturns the day of the year without leading spaces [0 through to 365]

Year Parameters

CharacterDescription
YFour-digit year
yTwo-digit year.

Hour Parameters

CharacterDescription
hHour in 12-hour format, with leading zero (two digits).
HHour in 24-hour format, with leading zero (two digits).
gHour in 12-hour format (no leading zero).
GHour in 24-hour format (no leading zero).
aam/pm (lowercase).
AAM/PM (uppercase).
OString representation of the difference in hours between local time and GMT/UTC (for example, +1000, –0500).

Minute Parameters

CharacterDescription
iMinute, with leading zero (two digits).
jMinute (no leading zero).

Second Parameters

CharacterDescription
sSecond, with leading zero (two digits).
Z

Integer representation of the difference in seconds between local time and GMT/UTC

(for example, 36000 for GMT+1000 and –18000 for GMT– 0500).

Complete Date and Time

CharacterDescriptionExample
cISO-8601 format (YYYY-MM-DDTHH:MM:SS±HHMM)2005-03-14T19:38:08+10:00
rRFC-2822 format WWW, DD MMM YYYY HH:MM:SS ±HHMMMon,14 Mar 2005 19:38:08 +1000
U

Seconds since the Unix epoch.

Calling date('U') with no timestamp argument produces the same output as the time() function.

-

Displaying Human-Readable Dates and Times

To obtain a timestamp for the current system date and time, it is necessary only to call the time() function, as shown here.

<?php
	echo time();
?>

In a web browser, this produces output such as the following: 1110638611

For obtaining a human-readable date and time, PHP provides the date() function.

When called with a single argument (a formatting string), this function returns a string representation of the current date and/or time. The optional second argument is a timestamp.

Example:

<?php
	$time = time();
	$formats = array(
		'U',
		'r','c',
		'l, F jS, Y, g:i A',
		'H:i:s D d M y',
	);
	foreach($formats as $format)
	echo "<p><b>$format</b>: " . date($format, $time) . "</p>\n";
?>

Output:

U: 1110643578
r: Sun, 13 Mar 2005 02:06:18 +1000
c: 2005-03-13T02:06:18+10:00
l, F jS, Y, g:i A: Sunday, March 13th, 2005, 2:06 AM
H:i:s D d M y: 02:06:18 Sun 13 Mar 05