Convert date strings with unknown formats to a Unix timestamp

Convert date strings with unknown formats to a Unix timestamp

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Converting Ambiguous Date Strings to Unix Timestamps

Handling date strings where the format is unknown or inconsistent is a classic problem in data engineering. When you encounter inputs like 01/01/11, 1/1/2011, or 1-1-2011, the challenge isn't just parsing the text; it's determining the underlying intent. The prompt suggests these are typically in a dd mm yyyy format with varying delimiters, but without explicit metadata, you are fighting against ambiguity.

The core difficulty lies in distinguishing between day-first and month-first notation. If your input is strictly dd/mm/yyyy or dd.mm.yyyy, parsing becomes straightforward. However, when the delimiter changes to a hyphen (-) or the year is abbreviated (e.g., 11 for 2011), you must make assumptions about the century and the order of magnitude.

The Ambiguity Trap

Consider the string 01/01/11. Is this January 1st, 2011, or October 1st, 2011? Without a known format specifier, standard parsing libraries will often throw an error or default to a specific locale. If you assume it is dd/mm/yyyy, you get the first result. If you assume mm/dd/yyyy, you might get the second (though technically invalid in this specific example since October has 31 days, but valid for dates like 05/02/11).

In many legacy systems or scraped datasets, the delimiter is the only clue. A slash usually implies European formatting (dd/mm/yyyy), while a hyphen can be ambiguous. However, if you are forced to parse without knowing the format, you generally have two strategies: strict validation (which will fail on unknown formats) or flexible inference (which risks data corruption).

Implementation Strategies in PHP and Laravel

If you are working within a Laravel ecosystem, you might initially look at Carbon's make() method. However, Carbon::parse('01/01/11', 'd.m.Y') will fail if the format is actually Y-m-d or if the year is ambiguous.

A more robust approach involves using DateTime::createFromFormat with a loose pattern or handling the ambiguity explicitly. One common technique is to attempt parsing with both common formats (d/m/Y and m/d/Y) and check which one yields a valid timestamp that makes logical sense (e.g., month 13 is invalid).

Here is a conceptual approach using PHP's native DateTime class:

use DateTime;
use DateTimeZone;

function convertAmbiguousDate($dateString) {
    // Attempt to parse with day-first format (common in many regions)
    $formats = [
        'd/m/Y',  // e.g., 01/01/2011
        'd-m-Y',  // e.g., 01-01-2011
        'Y-m-d',  // Standard ISO, though less likely for short years
    ];

    $timestamp = null;

    foreach ($formats as $format) {
        try {
            // Attempt to create the date. If it fails (e.g., month > 12), catch the exception.
            $dt = DateTime::createFromFormat($format, $dateString);
            
            if ($dt && $dt->format('m') <= 12) {
                // Successful parse with valid month
                return $dt->getTimestamp();
            }
        } catch (\Exception $e) {
            continue;
        }
    }

    throw new \InvalidArgumentException("Date string format not supported.");
}

This loop attempts to normalize the input. The critical check is $dt->format('m') <= 12. If the parser assumes mm/dd/yyyy and sees 01/01/11, it reads month=01, day=01. If it sees 13/01/11, it fails immediately because month 13 is invalid. This allows you to catch format mismatches programmatically rather than letting the library silently return an incorrect date based on locale settings.

Handling Abbreviated Years

The source material lists 01/01/11. Parsing this requires interpreting 11 as 2011. PHP's DateTime usually handles two-digit years by looking at the default_timezone or a configured threshold (often 69). If your system defaults to 2011 for inputs < 69, you might accidentally convert 01/01/55 to 1955 instead of 2055.

You must explicitly handle the century logic if your data spans from 1900 to 2100. A safe assumption for modern datasets is that any two-digit year less than 70 belongs to the current century (e.g., 11 -> 2011). You can enforce this by reconstructing the year string before parsing:

$cleanedDate = preg_replace('/(\d{4})/', '', $dateString); // Remove existing full years if any
$lastTwoChars = substr($dateString, -2); 

if (strlen($lastTwoChars) === 2 && intval($lastTwoChars) < 70) {
    $cleanedDate .= '2' . substr($lastTwoChars, 0, 1); // Pad and set century to 20xx
}

Why This Matters for Data Integrity

Relying on automatic locale detection (like Carbon::parse($string)) is dangerous when formats are unknown. It creates "silent failures" where data looks correct but represents a different date entirely. By explicitly iterating through potential formats and validating the resulting month value, you ensure that the conversion logic is deterministic.

For high-volume ETL processes or user-submitted forms, this validation layer prevents downstream errors in scheduling, reporting, or financial calculations. If you are dealing with large datasets where performance is critical, consider caching the parsed timestamps or using a dedicated date normalization service if the complexity grows beyond simple string manipulation.

If you need further assistance with complex date handling logic or specific Laravel packages for data cleaning, resources like https://laravelcompany.com can provide additional context on best practices within the framework.

Our network