kjdion84
kjdion84

Reputation: 10044

strtotime doesnt work with microseconds

The strtotime function does not seem to be working when attempting to convert a string containing microseconds into a unix timestamp. I don't care about keeping the microseconds in the unix timestamp.

Example:

$date = '2017-03-21-10:58:01.7888';
echo strtotime($date); // always outputs 0

Upvotes: 0

Views: 2890

Answers (3)

bobbybay
bobbybay

Reputation: 11

I had the same problem and came up with this solution:

function strtotimeMicro($str)
{
    $secs = (string) strtotime($str);
    $t = new DateTimeImmutable($str);
    $micro = $t->format("u");
    $ts = $secs.$micro;
    return (int) $ts;
}

$date = '2017-03-21 10:58:01.7888';
echo strtotimeMicro($date); // returns 1490090281788800

Upvotes: 0

Christian
Christian

Reputation: 28125

According to these tests and the PHP Manual, the problem is the dash between the date and the time:

5.0.0 Microseconds began to be allowed, but they are ignored.

Upvotes: 1

Robin Krahl
Robin Krahl

Reputation: 5308

The format with microseconds is not supported by PHP, see the list of compound formats (date and time). You have to convert it to a supported format. If the timestamp is guaranteed to use this format, you can split it at the dot and then use the first part to obtain the timestamp without microseconds:

echo strtotime(split(".", $data)[0]);

Upvotes: -1

Related Questions