Search code examples
phpdatetimeiso8601

Subtract milliseconds from ISO 8601 date string in PHP


I'm having a devil of a time working with what I think (?) are ISO 8601 date strings. I need to be able to subtract milliseconds from them, so that I can do something like this:

$a = '2019-06-09T12:56:52.081Z';

$b = subtract_milliseconds($a, 1);

echo $b; // '2019-06-09T12:56:52.080Z';

Any help would be greatly appreciated, thanks!


Solution

  • Something like this:

    $d = new DateTime('2019-06-09T12:56:52.081Z');
    $d->setTime($d->format('H'), $d->format('i'), $d->format('s'), $d->format('u') - 1000);
    echo $d->format('Y-m-d\TH:i:s.u\Z');
    // 2019-06-09T12:56:52.080000Z
    

    Note that this only works since PHP 7.1, solutions for older PHP versions would probably be a lot more manual.