PHP Date and Time

Working with dates, times, and timestamps

🕐 What is PHP Date and Time?

PHP provides powerful functions to work with dates and times. You can display current date, format timestamps, calculate date differences, and manipulate time values for various applications.


<?php
// Display current date
echo date("Y-m-d");
// Output: 2025-10-02
?>
                                    

Date and Time Functions

📅

date()

Format current date and time

<?php
echo date("Y-m-d");
// 2025-10-02
?>

time()

Get current Unix timestamp

<?php
echo time();
// 1727884800
?>
🔄

strtotime()

Convert string to timestamp

<?php
echo strtotime("next Monday");
?>
📆

mktime()

Create custom timestamp

<?php
echo mktime(0, 0, 0, 12, 25, 2025);
?>

🔹 Basic Date Display

Display current date in various formats:

<?php
// Current date in different formats
echo "Today is " . date("Y-m-d") . "<br>";
// Output: Today is 2025-10-02

echo "Today is " . date("d/m/Y") . "<br>";
// Output: Today is 02/10/2025

echo "Today is " . date("l, F j, Y") . "<br>";
// Output: Today is Thursday, October 2, 2025

echo "Current time is " . date("h:i:s A") . "<br>";
// Output: Current time is 03:30:45 PM

echo "Current date and time: " . date("Y-m-d H:i:s") . "<br>";
// Output: Current date and time: 2025-10-02 15:30:45
?>

🔹 Date Format Characters

Common format characters for the date() function:

Day Formats:

  • d - Day of month (01-31)
  • j - Day of month without leading zeros (1-31)
  • D - Day name, 3 letters (Mon, Tue, Wed)
  • l - Full day name (Monday, Tuesday)

Month Formats:

  • m - Month number (01-12)
  • n - Month without leading zeros (1-12)
  • M - Month name, 3 letters (Jan, Feb)
  • F - Full month name (January, February)

Year Formats:

  • Y - 4-digit year (2025)
  • y - 2-digit year (25)

Time Formats:

  • H - 24-hour format (00-23)
  • h - 12-hour format (01-12)
  • i - Minutes (00-59)
  • s - Seconds (00-59)
  • A - AM or PM
<?php
echo date("d") . "<br>";      // 02
echo date("D") . "<br>";      // Thu
echo date("l") . "<br>";      // Thursday
echo date("m") . "<br>";      // 10
echo date("M") . "<br>";      // Oct
echo date("F") . "<br>";      // October
echo date("Y") . "<br>";      // 2025
echo date("H:i:s") . "<br>";  // 15:30:45
?>

🔹 Working with Timestamps

Unix timestamp represents seconds since January 1, 1970:

<?php
// Get current timestamp
$timestamp = time();
echo "Current timestamp: " . $timestamp . "<br>";
// Output: Current timestamp: 1727884800

// Convert timestamp to readable date
echo "Date: " . date("Y-m-d H:i:s", $timestamp) . "<br>";
// Output: Date: 2025-10-02 15:30:45

// Create timestamp for specific date
$christmas = mktime(0, 0, 0, 12, 25, 2025);
echo "Christmas 2025: " . date("l, F j, Y", $christmas) . "<br>";
// Output: Christmas 2025: Thursday, December 25, 2025

// Convert string to timestamp
$nextWeek = strtotime("+1 week");
echo "Next week: " . date("Y-m-d", $nextWeek) . "<br>";
// Output: Next week: 2025-10-09
?>

🔹 Date Calculations

Perform calculations with dates using strtotime():

<?php
// Current date
$today = date("Y-m-d");
echo "Today: " . $today . "<br>";

// Tomorrow
$tomorrow = date("Y-m-d", strtotime("+1 day"));
echo "Tomorrow: " . $tomorrow . "<br>";

// Next week
$nextWeek = date("Y-m-d", strtotime("+1 week"));
echo "Next week: " . $nextWeek . "<br>";

// Next month
$nextMonth = date("Y-m-d", strtotime("+1 month"));
echo "Next month: " . $nextMonth . "<br>";

// Last year
$lastYear = date("Y-m-d", strtotime("-1 year"));
echo "Last year: " . $lastYear . "<br>";

// Specific date
$specificDate = date("Y-m-d", strtotime("2025-12-25"));
echo "Christmas: " . $specificDate . "<br>";

// Next Monday
$nextMonday = date("Y-m-d", strtotime("next Monday"));
echo "Next Monday: " . $nextMonday . "<br>";
?>

🔹 Calculate Date Difference

Find the difference between two dates:

<?php
// Method 1: Using timestamps
$date1 = strtotime("2025-10-02");
$date2 = strtotime("2025-12-25");

$diff = $date2 - $date1;
$days = floor($diff / (60 * 60 * 24));

echo "Days until Christmas: " . $days . " days<br>";
// Output: Days until Christmas: 84 days

// Method 2: Using DateTime objects
$datetime1 = new DateTime("2025-10-02");
$datetime2 = new DateTime("2025-12-25");

$interval = $datetime1->diff($datetime2);
echo "Difference: " . $interval->days . " days<br>";
echo "Or: " . $interval->m . " months and " . $interval->d . " days<br>";

// Calculate age
$birthdate = new DateTime("1990-05-15");
$today = new DateTime();
$age = $birthdate->diff($today);
echo "Age: " . $age->y . " years old<br>";
?>

🔹 DateTime Class

Object-oriented approach to working with dates:

<?php
// Create DateTime object
$date = new DateTime();
echo "Current date: " . $date->format('Y-m-d H:i:s') . "<br>";

// Create specific date
$specificDate = new DateTime('2025-12-25');
echo "Christmas: " . $specificDate->format('l, F j, Y') . "<br>";

// Modify date
$date->modify('+1 month');
echo "Next month: " . $date->format('Y-m-d') . "<br>";

$date->modify('-2 weeks');
echo "Two weeks ago: " . $date->format('Y-m-d') . "<br>";

// Set timezone
$date->setTimezone(new DateTimeZone('America/New_York'));
echo "New York time: " . $date->format('Y-m-d H:i:s T') . "<br>";

// Add interval
$date->add(new DateInterval('P10D')); // Add 10 days
echo "After 10 days: " . $date->format('Y-m-d') . "<br>";
?>

🔹 Timezone Handling

Work with different timezones:

<?php
// Set default timezone
date_default_timezone_set('America/New_York');
echo "New York: " . date('Y-m-d H:i:s') . "<br>";

// Get all timezones
$timezones = DateTimeZone::listIdentifiers();
echo "Total timezones: " . count($timezones) . "<br>";

// Create date with specific timezone
$date = new DateTime('now', new DateTimeZone('Asia/Tokyo'));
echo "Tokyo: " . $date->format('Y-m-d H:i:s T') . "<br>";

// Convert between timezones
$date->setTimezone(new DateTimeZone('Europe/London'));
echo "London: " . $date->format('Y-m-d H:i:s T') . "<br>";

// Get timezone offset
$timezone = new DateTimeZone('America/Los_Angeles');
$datetime = new DateTime('now', $timezone);
$offset = $timezone->getOffset($datetime);
echo "UTC offset: " . ($offset / 3600) . " hours<br>";
?>

🔹 Practical Date Examples

Real-world date and time applications:

<?php
// Check if date is weekend
function isWeekend($date) {
    $dayOfWeek = date('N', strtotime($date));
    return ($dayOfWeek >= 6);
}

echo "Is today weekend? " . (isWeekend('2025-10-02') ? "Yes" : "No") . "<br>";

// Get first day of month
$firstDay = date('Y-m-01');
echo "First day of month: " . $firstDay . "<br>";

// Get last day of month
$lastDay = date('Y-m-t');
echo "Last day of month: " . $lastDay . "<br>";

// Count days in month
$daysInMonth = date('t');
echo "Days in this month: " . $daysInMonth . "<br>";

// Get week number
$weekNumber = date('W');
echo "Week number: " . $weekNumber . "<br>";

// Check if leap year
$year = 2024;
$isLeap = date('L', mktime(0, 0, 0, 1, 1, $year));
echo "$year is " . ($isLeap ? "a leap year" : "not a leap year") . "<br>";

// Format for database
$dbDate = date('Y-m-d H:i:s');
echo "Database format: " . $dbDate . "<br>";

// Human-readable time ago
function timeAgo($timestamp) {
    $diff = time() - $timestamp;
    if ($diff < 60) return $diff . " seconds ago";
    if ($diff < 3600) return floor($diff / 60) . " minutes ago";
    if ($diff < 86400) return floor($diff / 3600) . " hours ago";
    return floor($diff / 86400) . " days ago";
}

$pastTime = strtotime('-2 hours');
echo "Posted: " . timeAgo($pastTime) . "<br>";
?>

🧠 Test Your Knowledge

Which function returns the current Unix timestamp?