Date and time operations are fundamental in many programming applications, from logging events and scheduling tasks to displaying user-friendly information and calculating durations. PHP provides a robust set of functions and objects for handling dates and times, making it easy to manage these aspects.\n\nThe core of modern date/time handling in PHP revolves around the `DateTime` and `DateTimeImmutable` classes, along with `DateTimeZone` for time zone management and `DateInterval` for representing time durations. While older procedural functions like `date()`, `strtotime()`, `mktime()`, and `time()` are still available and widely used, the `DateTime` objects offer a more powerful, object-oriented, and less error-prone approach, especially for complex operations.\n\nKey aspects of date and time operations include:\n\n* Getting Current Date/Time: Obtaining the current server time or a specific timestamp.\n* Formatting Dates/Times: Displaying dates and times in various human-readable formats (e.g., "YYYY-MM-DD", "Month DD, YYYY HH:MM AM/PM").\n* Parsing Date Strings: Converting date strings (e.g., "2023-10-27 15:30:00") into a `DateTime` object or timestamp for manipulation.\n* Calculations: Adding or subtracting periods of time (e.g., 5 days, 2 hours, 1 month) from a given date.\n* Comparisons: Determining if one date is before, after, or the same as another.\n* Time Zones: Handling different time zones to ensure accurate time representation across geographical locations.\n* Timestamps: Working with Unix timestamps (the number of seconds since January 1, 1970, 00:00:00 UTC), which are useful for storage and internal calculations.\n\nPHP's `DateTime` objects offer a mutable (changeable) interface, meaning methods like `add()` or `sub()` modify the object itself. In contrast, `DateTimeImmutable` provides an immutable interface, where these methods return a *new* `DateTimeImmutable` object rather than modifying the original. This immutability is often preferred for predictability and avoiding side effects in complex codebases.
Example Code
<?php\n\n// 1. Getting the current date and time\necho "--- 1. Getting Current Date/Time ---\n";\n// Using date() function (procedural)\necho "Current date/time (date()): " . date("Y-m-d H:i:s") . "\n";\n// Using DateTime object (object-oriented, recommended)\n$now = new DateTime();\necho "Current date/time (DateTime): " . $now->format("Y-m-d H:i:s") . "\n";\necho "Current Unix timestamp: " . time() . "\n";\necho "DateTime object's timestamp: " . $now->getTimestamp() . "\n\n";\n\n\n// 2. Formatting Dates and Times\necho "--- 2. Formatting Dates and Times ---\n";\n$myDate = new DateTime('2023-01-15 10:30:00');\necho "Original date: " . $myDate->format("Y-m-d H:i:s") . "\n";\necho "Formatted (Full Date/Time): " . $myDate->format("l, F j, Y H:i:s A") . "\n"; // e.g., Friday, October 27, 2023 15:30:00 PM\necho "Formatted (Short Date): " . $myDate->format("m/d/y") . "\n"; // e.g., 10/27/23\necho "Formatted (ISO 8601): " . $myDate->format(DateTime::ISO8601) . "\n\n"; // Standard ISO format\n\n\n// 3. Parsing Date Strings\necho "--- 3. Parsing Date Strings ---\n";\n// Using strtotime() (procedural, flexible but can be ambiguous)\n$timestampFromString = strtotime("next Monday");\necho "Timestamp for 'next Monday': " . $timestampFromString . "\n";\necho "Date for 'next Monday': " . date("Y-m-d", $timestampFromString) . "\n\n";\n\n// Using DateTime::createFromFormat() (object-oriented, precise for known formats)\n$dateString = "15-03-2023 14:00";\n$dateFormat = "d-m-Y H:i";\n$parsedDate = DateTime::createFromFormat($dateFormat, $dateString);\nif ($parsedDate) {\n echo "Parsed date from '" . $dateString . "': " . $parsedDate->format("Y-m-d H:i:s") . "\n\n";\n} else {\n echo "Failed to parse date string: " . $dateString . "\n\n";\n}\n\n\n// 4. Date and Time Calculations\necho "--- 4. Date and Time Calculations ---\n";\n$startDate = new DateTime(); // Current date/time\necho "Start Date: " . $startDate->format("Y-m-d H:i:s") . "\n";\n\n// Add 1 month and 5 days\n$intervalAdd = new DateInterval('P1M5D'); // P = Period, 1M = 1 Month, 5D = 5 Days\n$futureDate = clone $startDate; // Clone to avoid modifying original $startDate if it were DateTime\n$futureDate->add($intervalAdd);\necho "Date + 1 Month 5 Days: " . $futureDate->format("Y-m-d H:i:s") . "\n";\n\n// Subtract 2 weeks and 3 hours\n$intervalSub = new DateInterval('P2W3H'); // P = Period, 2W = 2 Weeks, 3H = 3 Hours\n$pastDate = clone $startDate;\n$pastDate->sub($intervalSub);\necho "Date - 2 Weeks 3 Hours: " . $pastDate->format("Y-m-d H:i:s") . "\n\n";\n\n\n// 5. Comparing Dates\necho "--- 5. Comparing Dates ---\n";\n$date1 = new DateTime('2023-10-20');\n$date2 = new DateTime('2023-10-25');\n$date3 = new DateTime('2023-10-20');\n\necho "Date 1: " . $date1->format("Y-m-d") . "\n";\necho "Date 2: " . $date2->format("Y-m-d") . "\n";\necho "Date 3: " . $date3->format("Y-m-d") . "\n";\n\nif ($date1 < $date2) {\n echo "Date 1 is before Date 2.\n";\n}\nif ($date1 == $date3) { // Note: direct comparison works for exact time, use diff() or timestamps for just date parts\n echo "Date 1 is the same as Date 3 (including time if specified).\n";\n}\nif ($date2 > $date1) {\n echo "Date 2 is after Date 1.\n";\n}\n\n// Difference between two dates\n$diff = $date1->diff($date2);\necho "Difference between Date 1 and Date 2: " . $diff->days . " days.\n\n";\n\n\n// 6. Time Zones\necho "--- 6. Time Zones ---\n";\n// Get default timezone\necho "Default Timezone: " . date_default_timezone_get() . "\n";\n\n// Set a different timezone\n$londonTimezone = new DateTimeZone('Europe/London');\n$tokyoTimezone = new DateTimeZone('Asia/Tokyo');\n\n$utcDate = new DateTime('now', new DateTimeZone('UTC'));\necho "UTC Time: " . $utcDate->format("Y-m-d H:i:s") . "\n";\n\n$londonDate = clone $utcDate;\n$londonDate->setTimezone($londonTimezone);\necho "London Time: " . $londonDate->format("Y-m-d H:i:s") . " (" . $londonDate->format('T') . ")\n";\n\n$tokyoDate = clone $utcDate;\n$tokyoDate->setTimezone($tokyoTimezone);\necho "Tokyo Time: " . $tokyoDate->format("Y-m-d H:i:s") . " (" . $tokyoDate->format('T') . ")\n\n";\n\n\n// 7. Unix Timestamps\necho "--- 7. Unix Timestamps ---\n";\n$currentTimestamp = time(); // Current Unix timestamp\necho "Current Unix timestamp: " . $currentTimestamp . "\n";\n\n// Convert timestamp to DateTime object\n$dateTimeFromTimestamp = new DateTime();\n$dateTimeFromTimestamp->setTimestamp($currentTimestamp);\necho "DateTime from timestamp: " . $dateTimeFromTimestamp->format("Y-m-d H:i:s") . "\n";\n\n// Convert DateTime object to timestamp\n$anotherDate = new DateTime('2024-06-01 12:00:00');\necho "Date '2024-06-01 12:00:00' as timestamp: " . $anotherDate->getTimestamp() . "\n";\n\n// mktime() for creating timestamp from specific date/time components\n$specificTimestamp = mktime(10, 30, 0, 7, 21, 2023); // Hour, Minute, Second, Month, Day, Year\necho "Timestamp for 2023-07-21 10:30:00: " . $specificTimestamp . "\n";\necho "Date for that timestamp: " . date("Y-m-d H:i:s", $specificTimestamp) . "\n";\n\n?>








Date and Time Operations