The PHP Date and Time
The PHP Date and Time
Syntax
date(format,timestamp)
Parameter Description
timestamp Optional. Specifies a timestamp. Default is the current date and time
A timestamp is a sequence of characters, denoting the date and/or time at which a cer
Here are some characters that are commonly used for dates:
Example
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Run example »
Example
© 2010-<?php echo date("Y");?>
Run example »
The example below outputs the current time in the specified format:
Example
<?php
echo "The time is " . date("h:i:sa");
?>
Run example »
Note that the PHP date() function will return the current date/time of the server!
So, if you need the time to be correct according to a specific location, you can
set a timezone to use.
The example below sets the timezone to "America/New_York", then outputs the
current time in the specified format:
Example
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
Run example »
Syntax
mktime(hour,minute,second,month,day,year)
The example below creates a date and time from a number of parameters in the
mktime() function:
Example
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
Run example »
Syntax
strtotime(time,now)
The example below creates a date and time from the strtotime() function:
Example
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
Run example »
PHP is quite clever about converting a string to a date, so you can put in various
values:
Example
<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>
Run example »
However, strtotime() is not perfect, so remember to check the strings you put in
there.
Example
<?php
$startdate = strtotime("Saturday");
$enddate = strtotime("+6 weeks", $startdate);
Run example »
The example below outputs the number of days until 4th of July:
Example
<?php
$d1=strtotime("July 04");
$d2=ceil(($d1-time())/60/60/24);
echo "There are " . $d2 ." days until 4th of July.";
?>
Run example »
The reference contains a brief description, and examples of use, for each
function!