Search code examples
phpdateinfluxdb

Convert influxdb time format to ISO8601 format


When using the influxdb PHP client I see this time format with nanosecond precision:

2020-02-06T17:26:38.277740846Z

PHP DateTime does not seem to understand the format:

$date = DateTime::createFromFormat("Y-m-d\TH:i:s.u?",$time);

I get false as the return value.

How can I convert this to ISO8601 or a custom format?


Solution

  • As PHP dates don't handle more than the microseconds, you can ignore the rest of your string after the 6 digits of the microseconds with the + specifier

    From the documentation :

    +

    If this format specifier is present, trailing data in the string will not cause an error, but a warning instead

    Use DateTime::getLastErrors() to find out whether trailing data was present.

    If your dates always end with 'Z', you can force the UTC timezone :

    $time = '2020-02-06T17:26:38.277740846Z' ;
    $date = DateTime::createFromFormat("Y-m-d\TH:i:s.u+", $time, new DateTimeZone('UTC'));
    echo $date->format('c'); // 2020-02-06T17:26:38+00:00