Search code examples
phpdatetimeopensslx509

DateTime::__construct(): Failed to parse time string (131022120001Z) but the values comes from openssl_x509_parse()


I'm using openssl_x509_parse() to parse a digital certificate.

I've written an entity class that reads the array and transforms the values in objects.

So, for dates I use \DateTime().

The problem is that sometimes the object creation doesn't fail and sometimes it does.

So, for example, if I get the digital certificate of Google.com, I get as result the following array:

...
"validFrom" => "151118151813Z"
"validTo" => "160216000000Z"
"validFrom_time_t" => 1447859893
"validTo_time_t" => 1455580800
...

Those strings cause an error:

DateTime::__construct(): Failed to parse time string (1474632000) at position 8 (0): Unexpected character

I don't understand how to transform them into a DateTime object. What I'm doing wrong?


Solution

  • String 151118151813Z is datetime represented as ymdHis in Zulu timezone, which you can parse as:

    $dt = DateTime::createFromFormat('ymdHise', '151118151813Z');
    echo $dt->format('c');
    

    demo

    Or just use unix timestamp format 1447859893:

    $dt = new DateTime('@1447859893');
    echo $dt->format('c');
    

    demo

    In both examples you get same output.