SyntaxStudy
Sign Up
PHP Parsing Dates with strtotime
PHP Beginner 7 min read

Parsing Dates with strtotime

strtotime() converts an English textual datetime description into a Unix timestamp. It is extremely flexible and understands both absolute and relative formats.

  • Absolute: '2024-12-25', 'December 25, 2024', '25/12/2024'.
  • Relative: 'next Monday', '+3 weeks', 'last day of next month'.
  • Returns false on failure — always validate the result.
Example
<?php
// Absolute strings
echo date('Y-m-d', strtotime('2024-12-25'));         // 2024-12-25
echo date('Y-m-d', strtotime('December 25, 2024')); // 2024-12-25

// Relative strings
echo date('Y-m-d', strtotime('+7 days'));        // 7 days from now
echo date('Y-m-d', strtotime('-1 month'));       // 1 month ago
echo date('Y-m-d', strtotime('next Monday'));    // upcoming Monday
echo date('Y-m-d', strtotime('last Sunday'));    // previous Sunday
echo date('Y-m-d', strtotime('first day of next month'));
echo date('Y-m-d', strtotime('last day of this month'));

// Relative to a base timestamp (second argument)
$base = strtotime('2024-01-15');
echo date('Y-m-d', strtotime('+1 month', $base)); // 2024-02-15

// Validate
$ts = strtotime('not a date');
if ($ts === false) {
    echo 'Invalid date string';
}
Pro Tip

Tip: Avoid ambiguous formats like '01/02/03' — strtotime may interpret them differently across locales. Stick to ISO 8601 (YYYY-MM-DD) for unambiguous parsing, or use DateTimeImmutable::createFromFormat() for non-standard formats.