</>
Skip to content
PHP lessons (26/49)

PHP — Date and Time

Current date/time

<?php
echo date("Y-m-d");           // 2026-08-23
echo date("Y-m-d H:i:s");     // 2026-08-23 14:30:00
echo date("l, F j, Y");       // Saturday, August 23, 2026

// Timestamp
echo time();                   // Unix timestamp
echo microtime();              // With microseconds
?>

Creating dates

<?php
// From string
$date = new DateTime("2026-08-23");
echo $date->format("Y-m-d");

// From timestamp
$date = new DateTime("@1692787200");

// Create specific
$date = new DateTime("2026-12-25 10:30:00");
?>

Date arithmetic

<?php
$date = new DateTime("2026-08-23");

// Add
$date->modify("+1 month");
$date->modify("+7 days");

// Interval
$interval = new DateInterval("P1Y2M3D");
$date->add($interval);

// Difference
$date1 = new DateTime("2026-08-23");
$date2 = new DateTime("2026-12-25");
$diff = $date1->diff($date2);
echo $diff->days; // days between
?>

Timezone

<?php
date_default_timezone_set("America/New_York");
echo date("Y-m-d H:i:s");

// Different timezone
$date = new DateTime("now", new DateTimeZone("Europe/London"));
echo $date->format("Y-m-d H:i:s");
?>

Mini Practice

Write PHP code that:

  1. Gets current date in various formats
  2. Creates a DateTime object
  3. Performs date arithmetic
  4. Handles timezones

Up Next

In the next lesson, you'll learn about Math Functions — mathematical operations.

Related Topics

Frequently Asked Questions about Date and Time

What is Date and Time in PHP?

Date and Time is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Date and Time?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Date and Time.

Why is Date and Time important in PHP?

Date and Time is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.