Skip to content
Advertisement

Convert timestamp with dots in PHP (“yyyy.mm.dd hh:nn:ss.zzz”)

I’m trying to convert strings with hungarian datetime format, but no success because of the dot-separators:

<?php
$dtime = DateTime::createFromFormat("YY'.'MM'.'DD HH:MM:II frac", "2020.07.22 22:41:36.258");
$timestamp = $dtime->getTimestamp();
echo("Result: " . $timestamp . "<br>");
?>

Isn’t it possible without “string-replace” like this:
strtotime(preg_replace("/([0-9]{4}).([0-9]{2}).([0-9]{2})/",'${1}-${2}-${3}',$xml->delivery_time)) ?

(I’m new to PHP 5 and I’m shocked it can not simply convert a common date format. Searched 200+ results, wasted 4+ hours … no success.)

Advertisement

Answer

This solution will also work for PHP versions below 7.3

// convert a hungarian datetime to a timestamp
function toTimestamp($dt)
{
    $format = 'Y.m.d H:i:s.';
    
    if (version_compare(PHP_VERSION, '7.3.0', '<')) {
        $dt = explode('.', $dt);
        $dt[3] = intval($dt[3] * 1000);
        $dt = implode('.', $dt);

        $format .= 'u';
    } else {
        $format .= 'v';
    }

    return DateTime::createFromFormat($format, $dt)->getTimestamp();
}

$timestamp = toTimestamp('2020.07.22 22:41:36.258');
var_dump($timestamp);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement