PHP Date and Time
Date() function
A timestamp is converted to a more readable date and time using the PHP date()
feature.
The machine keeps track of dates and times using the UNIX Timestamp format, which tracks time in seconds since the Unix epoch began (midnight Greenwich Mean Time on January 1, 1970 i.e. January 1, 1970 00:00:00 GMT ).
Since this is an impractical format for humans to interpret, PHP converts a timestamp to a human-readable format and dates from your notation into a computer-readable timestamp. The date()
function in PHP has the following syntax.
date(format, timestamp)
The date()
function requires the format parameter, which defines the format of the returned date and time. The timestamp, on the other hand, is an optional parameter; if it is not specified, the current date and time will be used. The following statement shows the current date:
<?php
$today = date("d/m/Y");
echo $today;
?>
Time() function
To get the current time as a Unix timestamp, use the time()
feature (the number of seconds since the beginning of the Unix epoch: January 1 1970 00:00:00 GMT).
<?php
// Executed at
// March 05, 2014 07:19:18
$timestamp = time();
echo($timestamp);
?>
Output
1619471088
By passing this timestamp to the previously mentioned date()
feature, we can convert it to a human readable date
<?php
$timestamp = 1394003958;
echo(date("F d, Y h:i:s", $timestamp));
?>
Output
March 05, 2014 07:19:18
mktime() function
The timestamp is created using the mktime()
feature, which is based on a given date and time. The timestamp for the current date and time is returned if no date and time are given.
The mktime()
function has the following syntax:
mktime(hour, minute, second, month, day, year)
The timestamp for 3:20:12 pm
on May 10, 2014
is displayed in the following example:
<?php
// Create the
// timestamp for
// a particular date
echo mktime(15, 20, 12, 5, 10, 2014);
?>
Output
1399735212