PHP Date & Time Functions
Complete Guide in Hindi
PHP Date & Time की पूरी जानकारी — date(), time(), mktime(), strtotime(), DateTime class, DateInterval, Timezone handling। Real examples के साथ।
📋 इस Article में क्या-क्या है
- Unix Timestamp क्या है?
- time() — Current Timestamp
- date() — Format करना
- mktime() — Custom Timestamp
- strtotime() — String → Timestamp
- Date Arithmetic
- DateTime Class (OOP)
- DateInterval & DatePeriod
- Timezone Handling
- Real World Examples
Unix Timestamp — 1 January 1970, 00:00:00 UTC से अब तक के seconds की count। PHP में dates internally timestamp के रूप में store होती हैं — एक single integer number।
// 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 नहीं
?>
$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";
?>
// timestamp null = current time
| Character | मतलब | Example Output |
|---|---|---|
| Y | 4-digit year | 2025 |
| y | 2-digit year | 25 |
| m | Month (01-12) | 05 |
| n | Month (1-12, no zero) | 5 |
| M | Month short (Jan-Dec) | May |
| F | Month full | May |
| d | Day (01-31) | 15 |
| j | Day (1-31, no zero) | 15 |
| D | Day short (Mon-Sun) | Thu |
| l | Day full | Thursday |
| H | Hour 24h (00-23) | 14 |
| h | Hour 12h (01-12) | 02 |
| i | Minutes (00-59) | 30 |
| s | Seconds (00-59) | 45 |
| A | AM/PM | PM |
| a | am/pm | pm |
| U | Unix timestamp | 1716768000 |
| N | Day of week (1=Mon, 7=Sun) | 4 |
| W | Week number of year | 20 |
| t | Days in month | 31 |
| L | Leap year (1/0) | 0 |
// 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)
?>
// 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";
?>
// 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"));
?>
// 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";
}
?>
// 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 दिन बाकी हैं";
?>
// 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
?>
// 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
?>
$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
?>
// 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
?>
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 घंटे पहले"
?>
| Function | काम | Returns | Use Case |
|---|---|---|---|
| time() | Current Unix timestamp | int | Expiry check, duration |
| microtime() | Microseconds timestamp | float | Performance measure |
| date($fmt) | Timestamp → formatted string | string | Display dates |
| mktime() | Date parts → timestamp | int | Custom date timestamp |
| strtotime() | String → timestamp | int|false | Natural language dates |
| checkdate() | Date valid है? | bool | Form validation |
| new DateTime() | DateTime object बनाना | DateTime | OOP date handling |
| new DateTimeImmutable() | Immutable DateTime | DateTimeImmutable | Safe date operations |
| $dt->diff() | Two dates का difference | DateInterval | Age, duration |
| $dt->modify() | Date modify करना | DateTime | +1 month, -2 days |
| date_default_timezone_set() | Default timezone set | bool | App 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।