PHP Basics · Chapter 12 · Date & Time

PHP Date & Time Functions
Complete Guide in Hindi

PHP Date & Time की पूरी जानकारी — date(), time(), mktime(), strtotime(), DateTime class, DateInterval, Timezone handling। Real examples के साथ।

📅 date() ⏱️ time() 🔄 strtotime() 🏗️ DateTime class 🌍 Timezone
UnixTimestamp — seconds since 1970
date()Timestamp → String
strtotimeString → Timestamp
DateTimeOOP Style — recommended

📋 इस Article में क्या-क्या है

  1. Unix Timestamp क्या है?
  2. time() — Current Timestamp
  3. date() — Format करना
  4. mktime() — Custom Timestamp
  5. strtotime() — String → Timestamp
  6. Date Arithmetic
  7. DateTime Class (OOP)
  8. DateInterval & DatePeriod
  9. Timezone Handling
  10. Real World Examples
1
Unix Timestamp क्या है?

Unix Timestamp — 1 January 1970, 00:00:00 UTC से अब तक के seconds की count। PHP में dates internally timestamp के रूप में store होती हैं — एक single integer number।

Timestamp = एक बड़ा integer। जैसे 1700000000 = November 14, 2023। किसी भी format में convert करो।
UNIX TIMESTAMP — BASICS
<?php
// Current timestamp
echo time(); // e.g. 1716768000

// Timestamp को date में convert
echo date("Y-m-d", 0); // 1970-01-01 (epoch start)
echo date("Y-m-d", 1700000000); // 2023-11-14

// 32-bit limit — Y2K38 problem
// Max 32-bit: 2147483647 = January 19, 2038
// 64-bit PHP में कोई limit नहीं
?>

2
time() — Current Unix Timestamp
time
()

time()

Current Unix timestamp return करता है — अभी के seconds। Date calculations, expiry check, duration measure — सब में ज़रूरी।

PHP 4+ Returns: int UTC based
time() — EXAMPLES
<?php
$now = time();
echo $now; // e.g. 1716768000

// Future timestamps
$oneHourLater = time() + 3600; // +1 hour
$oneDayLater = time() + 86400; // +1 day
$oneWeekLater = time() + (7 * 86400); // +7 days
$oneMonthLater = strtotime("+1 month"); // More accurate

// Session expiry check
$loginTime = 1716768000; // stored login time
$sessionLife = 1800; // 30 min in seconds
if (time() - $loginTime > $sessionLife) {
  echo "Session expired! Please login again.";
}

// Performance measure
$start = microtime(true); // float — milliseconds
// ... some code ...
$elapsed = microtime(true) - $start;
echo round($elapsed * 1000, 2) . " ms";
?>

3
date() — Timestamp को Format करना
date
()

date()

Unix timestamp को human-readable date string में convert करता है। Format characters से जो भी format चाहो बना सकते हो।

PHP 4+ Returns: string Timezone-aware
string date( string $format, ?int $timestamp = null )
// timestamp null = current time
CharacterमतलबExample Output
Y4-digit year2025
y2-digit year25
mMonth (01-12)05
nMonth (1-12, no zero)5
MMonth short (Jan-Dec)May
FMonth fullMay
dDay (01-31)15
jDay (1-31, no zero)15
DDay short (Mon-Sun)Thu
lDay fullThursday
HHour 24h (00-23)14
hHour 12h (01-12)02
iMinutes (00-59)30
sSeconds (00-59)45
AAM/PMPM
aam/pmpm
UUnix timestamp1716768000
NDay of week (1=Mon, 7=Sun)4
WWeek number of year20
tDays in month31
LLeap year (1/0)0
date() — COMMON FORMATS
<?php
// Current date/time
echo date("Y-m-d"); // 2025-05-15
echo date("d/m/Y"); // 15/05/2025
echo date("d-M-Y"); // 15-May-2025
echo date("D, d F Y"); // Thu, 15 May 2025
echo date("H:i:s"); // 14:30:45
echo date("h:i A"); // 02:30 PM
echo date("Y-m-d H:i:s"); // 2025-05-15 14:30:45 (DB format)
echo date("l, d F Y"); // Thursday, 15 May 2025

// Specific timestamp format
echo date("Y-m-d", 1700000000); // 2023-11-14

// Current year, month, day separately
echo date("Y"); // 2025
echo date("m"); // 05
echo date("d"); // 15
echo date("N"); // 4 (Thursday)
?>

4
mktime() — Custom Date का Timestamp
mkt
ime

mktime()

Specific date/time के components (hour, minute, second, month, day, year) से Unix timestamp बनाता है। किसी past/future date का timestamp चाहिए तो यही।

PHP 4+ Returns: int Custom date timestamp
int mktime( $hour, $minute, $second, $month, $day, $year )
mktime() — EXAMPLES
<?php
// 15 May 2025 का timestamp
$ts = mktime(0, 0, 0, 5, 15, 2025);
echo date("D, d M Y", $ts); // Thu, 15 May 2025

// Independence Day 2025
$independence = mktime(0, 0, 0, 8, 15, 2025);
echo date("l, d F Y", $independence);
// Friday, 15 August 2025

// Overflow handling — auto calculate
// Month 13 = next year January
$ts2 = mktime(0, 0, 0, 13, 1, 2025);
echo date("Y-m-d", $ts2); // 2026-01-01

// Days remaining in month
$daysInMonth = date("t"); // current month days
$today = date("j"); // current day
echo ($daysInMonth - $today) . " days remaining";
?>

5
strtotime() — English String → Timestamp
strt
otime

strtotime()

English date strings को Unix timestamp में convert करता है। "next Monday", "+1 month", "2025-05-15" — सब handle करता है। PHP का सबसे intelligent date function।

PHP 4+ Returns: int|false Natural Language
strtotime() — NATURAL LANGUAGE DATES
<?php
// Date strings
echo date("Y-m-d", strtotime("2025-05-15")); // 2025-05-15
echo date("Y-m-d", strtotime("15 May 2025")); // 2025-05-15
echo date("Y-m-d", strtotime("May 15, 2025")); // 2025-05-15

// Relative dates
echo date("Y-m-d", strtotime("today"));
echo date("Y-m-d", strtotime("yesterday"));
echo date("Y-m-d", strtotime("tomorrow"));
echo date("Y-m-d", strtotime("next Monday"));
echo date("Y-m-d", strtotime("last Friday"));
echo date("Y-m-d", strtotime("first day of this month"));
echo date("Y-m-d", strtotime("last day of this month"));
echo date("Y-m-d", strtotime("first day of next month"));

// Relative from now
echo date("Y-m-d", strtotime("+1 day"));
echo date("Y-m-d", strtotime("+1 week"));
echo date("Y-m-d", strtotime("+1 month"));
echo date("Y-m-d", strtotime("+1 year"));
echo date("Y-m-d", strtotime("-3 months"));
echo date("Y-m-d H:i:s", strtotime("+2 hours 30 minutes"));
?>
strtotime() — REAL WORLD
<?php
// 1. Subscription expiry
$startDate = "2025-05-15";
$expiryDate = date("Y-m-d", strtotime($startDate . " +1 year"));
echo "Expires: $expiryDate"; // 2026-05-15

// 2. OTP expiry — 10 minutes
$otpExpiry = date("Y-m-d H:i:s", strtotime("+10 minutes"));
echo "OTP valid till: $otpExpiry";

// 3. Is date expired?
$expiryTs = strtotime("2024-01-01");
if (time() > $expiryTs) {
  echo "❌ Expired";
}

// 4. Invalid string — returns false
$ts = strtotime("not a date");
if ($ts === false) {
  echo "Invalid date string";
}
?>
⚠️ strtotime() trap: Ambiguous dates जैसे "05/06/2025" — US format में May 6, European में June 5। हमेशा unambiguous format use करो: "2025-05-06" (ISO 8601) या "6 May 2025"।

6
Date Arithmetic — Dates के बीच Difference
DATE DIFFERENCE — Days, Months, Years
<?php
// Method 1 — Timestamps से (simple)
$date1 = strtotime("2025-01-01");
$date2 = strtotime("2025-05-15");
$diffSeconds = $date2 - $date1;
$diffDays = floor($diffSeconds / 86400);
echo $diffDays . " days"; // 134 days

// Age calculator
$dob = strtotime("2000-06-15");
$ageSeconds = time() - $dob;
$ageYears = floor($ageSeconds / (365.25 * 86400));
echo "Age: $ageYears years";

// Days until event
$event = strtotime("2025-08-15"); // Independence Day
$daysLeft = ceil(($event - time()) / 86400);
echo "Independence Day में $daysLeft दिन बाकी हैं";
?>

7
DateTime Class — OOP Style (Recommended)
DT
obj

DateTime / DateTimeImmutable

PHP 5.2+ का OOP date handling। Procedural date() से बेहतर — chainable methods, timezone support, immutable option। Modern PHP में यही use करो।

PHP 5.2+ OOP Style Recommended
DateTime — CREATE & FORMAT
<?php
// Create — current time
$now = new DateTime();
echo $now->format("Y-m-d H:i:s"); // 2025-05-15 14:30:45

// Create from string
$date = new DateTime("2025-05-15");
echo $date->format("D, d M Y"); // Thu, 15 May 2025

// createFromFormat — specific format parse
$date2 = DateTime::createFromFormat("d/m/Y", "15/05/2025");
echo $date2->format("Y-m-d"); // 2025-05-15

// modify — date change करना
$future = new DateTime();
$future->modify("+1 month");
$future->modify("+15 days");
echo $future->format("Y-m-d");

// getTimestamp()
echo $date->getTimestamp(); // Unix timestamp
?>
DateTimeImmutable — Safer Version
<?php
// DateTime — mutable, original changes
$dt = new DateTime("2025-05-15");
$dt->modify("+1 day"); // $dt changed to May 16

// DateTimeImmutable — original unchanged
$dti = new DateTimeImmutable("2025-05-15");
$next = $dti->modify("+1 day"); // New object
echo $dti->format("Y-m-d"); // 2025-05-15 (unchanged!)
echo $next->format("Y-m-d"); // 2025-05-16
?>
💡 DateTime vs DateTimeImmutable: Production code में DateTimeImmutable use करो — bugs कम होते हैं क्योंकि original object कभी नहीं बदलता। Functions में pass करने पर side effects नहीं।

8
DateInterval — Accurate Date Difference
DateInterval — diff() METHOD
<?php
$date1 = new DateTime("2000-06-15"); // DOB
$date2 = new DateTime(); // Today

// diff() — DateInterval object return
$interval = $date1->diff($date2);

echo $interval->y . " years\n"; // 24 years
echo $interval->m . " months\n"; // 11 months
echo $interval->d . " days\n"; // 0 days
echo $interval->days . " total days"; // 9101 total

// Format method
echo $interval->format("%y years, %m months, %d days");

// Create interval manually
$d = new DateTime();
$plus = new DateInterval("P1Y2M3D"); // 1 year 2 months 3 days
$d->add($plus);
echo $d->format("Y-m-d");

// DateInterval format: P[n]Y[n]M[n]DT[n]H[n]M[n]S
// P = Period, T = Time separator
// P1Y = 1 year, P1M = 1 month, P1D = 1 day
// PT1H = 1 hour, PT30M = 30 minutes
?>

9
Timezone Handling
TIMEZONE — SETUP & CONVERSION
<?php
// Default timezone set करना — ज़रूरी!
date_default_timezone_set("Asia/Kolkata");
echo date("Y-m-d H:i:s"); // IST time

// Current timezone
echo date_default_timezone_get(); // Asia/Kolkata

// DateTime — timezone aware
$ist = new DateTimeZone("Asia/Kolkata");
$utc = new DateTimeZone("UTC");
$ny = new DateTimeZone("America/New_York");

$dt = new DateTime("now", $ist);
echo "IST: " . $dt->format("H:i:s");

// Convert to UTC
$dt->setTimezone($utc);
echo "UTC: " . $dt->format("H:i:s");

// Convert to NY
$dt->setTimezone($ny);
echo "NY: " . $dt->format("H:i:s");

// Common Indian timezones
// Asia/Kolkata — India Standard Time (UTC+5:30)
// Asia/Karachi — Pakistan Standard Time
// Asia/Dhaka — Bangladesh Standard Time
?>
php.ini में default timezone: date.timezone = "Asia/Kolkata" set करो। हर script में date_default_timezone_set() call करने की ज़रूरत नहीं। लेकिन critical apps में explicit timezone set करना better practice है।

10
Real World Examples
COMBINED — Booking System Date Logic
<?php
date_default_timezone_set("Asia/Kolkata");

// 1. Booking validity check
function isBookingValid(string $checkIn, string $checkOut): bool {
  $in = new DateTimeImmutable($checkIn);
  $out = new DateTimeImmutable($checkOut);
  $today = new DateTimeImmutable("today");
  return $in >= $today && $out > $in;
}
var_dump(isBookingValid("2025-06-01", "2025-06-05")); // true
var_dump(isBookingValid("2024-01-01", "2024-01-05")); // false (past)

// 2. Duration और price
function calcBookingPrice(string $in, string $out, float $ratePerNight): array {
  $d1 = new DateTimeImmutable($in);
  $d2 = new DateTimeImmutable($out);
  $nights = $d1->diff($d2)->days;
  $total = $nights * $ratePerNight;
  return compact("nights", "total");
}
$booking = calcBookingPrice("2025-06-01", "2025-06-05", 2500);
echo "Nights: {$booking['nights']}, Total: ₹{$booking['total']}";
// Nights: 4, Total: ₹10000

// 3. Human-readable "time ago"
function timeAgo(string $datetime): string {
  $diff = time() - strtotime($datetime);
  return match(true) {
    $diff < 60 => "अभी-अभी",
    $diff < 3600 => floor($diff/60) . " मिनट पहले",
    $diff < 86400 => floor($diff/3600) . " घंटे पहले",
    $diff < 604800 => floor($diff/86400). " दिन पहले",
    default => date("d M Y", strtotime($datetime))
  };
}
echo timeAgo("2025-05-15 10:00:00"); // e.g. "3 घंटे पहले"
?>
Pattern: DateTimeImmutable (create) → diff() (difference) → format() (display) → timezone (global apps)

Quick Reference — Date Functions
FunctionकामReturnsUse Case
time()Current Unix timestampintExpiry check, duration
microtime()Microseconds timestampfloatPerformance measure
date($fmt)Timestamp → formatted stringstringDisplay dates
mktime()Date parts → timestampintCustom date timestamp
strtotime()String → timestampint|falseNatural language dates
checkdate()Date valid है?boolForm validation
new DateTime()DateTime object बनानाDateTimeOOP date handling
new DateTimeImmutable()Immutable DateTimeDateTimeImmutableSafe date operations
$dt->diff()Two dates का differenceDateIntervalAge, duration
$dt->modify()Date modify करनाDateTime+1 month, -2 days
date_default_timezone_set()Default timezone setboolApp startup

निष्कर्ष

PHP Date & Time handling powerful है। Bookings, subscriptions, age calculation, social media timestamps — सब में dates ज़रूरी हैं। OOP style prefer करो।

date_default_timezone_set("Asia/Kolkata") — हमेशा पहले set करो।

strtotime() — Natural language। "next Monday", "+1 month" सब काम करता है।

DateTimeImmutable — Production में prefer करो — side effects नहीं।

diff()->days — Accurate days difference। timestamp math से बेहतर।

ISO 8601 — Database में "Y-m-d H:i:s" format store करो — ambiguity नहीं।

UTC store, local display — DB में UTC, display में local timezone।

🚀 अगला Chapter: Chapter 13: PHP File Handling — fopen, fread, fwrite, file_get_contents, file_put_contents, directory functions। Files के साथ काम करना।