Backend Development

PHP Date and Time Examples

A complete reference guide to formatting, parsing, and manipulating dates and times using native PHP functions.

Format today's date in several ways

<?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");
?>

Automatically update copyright year

© 2010-<?php echo date("Y");?>

Output the current time (server time)

<?php
echo "The time is " . date("h:i:sa");
?>

Set timezone, then output time

<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>

Create a date/time using mktime()

<?php
// mktime(hour, minute, second, month, day, year)
$d = mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

Create a date/time using strtotime()

<?php
$d = strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

Relative dates with strtotime()

<?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>";
?>

Output dates for the next 6 Saturdays

<?php
$startdate = strtotime("Saturday");
$enddate = strtotime("+6 weeks", $startdate);

while ($startdate < $enddate) {
  echo date("M d", $startdate) . "<br>";
  // Increment by 1 week
  $startdate = strtotime("+1 week", $startdate);
}
?>

Calculate days until 4th of July

<?php
$d1 = strtotime("July 04");
$d2 = ceil(($d1 - time()) / 60 / 60 / 24);

echo "There are " . $d2 . " days until 4th of July.";
?>