PHP Script to Auto-Detect and Standardize Date Formats to YYYY-mm-dd

Answered using ChatGPT 4o by ChatGPT4o

Question:

PHP Auto Detect Date and Time Pattern YYYY, mm, dd in any shape and sort it as a standard one

Answer:

To auto-detect date and time patterns in PHP and standardize them, you can use regular expressions to identify different date formats and then convert them to a standard format, such as YYYY-mm-dd. Below is a PHP script that demonstrates how to achieve this:

<?php

function detectAndStandardizeDate($dateString) {
    // Define regex patterns for different date formats
    $patterns = [
        '/(\d{4})[-\/](\d{2})[-\/](\d{2})/', // YYYY-mm-dd or YYYY/mm/dd
        '/(\d{2})[-\/](\d{2})[-\/](\d{4})/', // dd-mm-YYYY or dd/mm/YYYY
        '/(\d{2})[-\/](\d{4})[-\/](\d{2})/', // mm-YYYY-dd or mm/YYYY/dd
        '/(\d{4})[-\/](\d{2})[-\/](\d{2})/', // YYYY-mm-dd or YYYY/mm/dd
    ];

    foreach ($patterns as $pattern) {
        if (preg_match($pattern, $dateString, $matches)) {
            // Check which pattern matched and rearrange accordingly
            if (count($matches) == 4) {
                if (strpos($pattern, '(\d{4})[-\/](\d{2})[-\/](\d{2})') !== false) {
                    // Pattern: YYYY-mm-dd or YYYY/mm/dd
                    return "{$matches[1]}-{$matches[2]}-{$matches[3]}";
                } elseif (strpos($pattern, '(\d{2})[-\/](\d{2})[-\/](\d{4})') !== false) {
                    // Pattern: dd-mm-YYYY or dd/mm/YYYY
                    return "{$matches[3]}-{$matches[2]}-{$matches[1]}";
                } elseif (strpos($pattern, '(\d{2})[-\/](\d{4})[-\/](\d{2})') !== false) {
                    // Pattern: mm-YYYY-dd or mm/YYYY/dd
                    return "{$matches[2]}-{$matches[1]}-{$matches[3]}";
                }
            }
        }
    }

    // If no pattern matched, return false or handle error
    return false;
}

// Test cases
$dates = [
    '2023-10-05',
    '05-10-2023',
    '10-2023-05',
    '2023/10/05',
    '05/10/2023',
    '10/2023/05',
];

foreach ($dates as $date) {
    $standardizedDate = detectAndStandardizeDate($date);
    if ($standardizedDate) {
        echo "Original: $date => Standardized: $standardizedDate\n";
    } else {
        echo "Original: $date => Invalid date format\n";
    }
}
?>

Explanation:

  1. Patterns: The script defines several regular expression patterns to match different date formats.
  2. Matching: It iterates through each pattern and uses preg_match to check if the date string matches the pattern.
  3. Rearranging: Depending on which pattern matched, it rearranges the date components to the standard YYYY-mm-dd format.
  4. Test Cases: The script includes test cases to demonstrate how it works with different date formats.

This script should cover the most common date formats. If you have additional formats, you can add more patterns to the $patterns array.