SyntaxStudy
Sign Up
PHP Date & Time Basics
PHP Beginner 6 min read

Date & Time Basics

PHP's procedural date functions have been available since PHP 4 and remain widely used. Understanding them is essential before moving to the OOP DateTime API.

  • time() returns the current Unix timestamp (seconds since 1970-01-01 00:00:00 UTC).
  • date($format, $timestamp) formats a timestamp as a string.
  • mktime() creates a timestamp from individual date/time components.
Example
<?php
// Current Unix timestamp
$now = time();
echo $now; // e.g. 1720000000

// Format current time
echo date('Y-m-d');            // 2024-07-15
echo date('d/m/Y H:i:s');     // 15/07/2024 14:30:00
echo date('l, F j, Y');       // Monday, July 15, 2024
echo date('D M j G:i:s T Y'); // Mon Jul 15 14:30:00 UTC 2024

// mktime(hour, minute, second, month, day, year)
$ts = mktime(0, 0, 0, 12, 25, 2024); // Christmas 2024 midnight
echo date('Y-m-d', $ts); // 2024-12-25

// Days until Christmas
$today = mktime(0, 0, 0, date('n'), date('j'), date('Y'));
$days  = ($ts - $today) / 86400;
echo "Days until Christmas: " . round($days);
Pro Tip

Tip: Common format characters: Y = 4-digit year, m = 2-digit month, d = 2-digit day, H = 24h hour, i = minutes, s = seconds, N = ISO weekday (1=Mon, 7=Sun), U = Unix timestamp.