5

If I have an object of type DateTime how I can add some milliseconds?

$date = new Datetime("2016-09-23T20:48:16.090Z");
// how to add to this date 9 milliseconds?
Cœur
  • 37,241
  • 25
  • 195
  • 267
nicolae-stelian
  • 344
  • 3
  • 12

2 Answers2

4

As of PHP 7.1, milliseconds and microseconds can also be easily added to DateTime using the modify method.

$date = new Datetime("2016-09-23T20:48:16.090Z");
$millisec = 9;

$date->modify('+ '.$millisec.' milliseconds');
var_dump($date);

Output:

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2016-09-23 20:48:16.099000"
  ["timezone_type"]=>
  int(2)
  ["timezone"]=>
  string(1) "Z"
}
jspit
  • 7,276
  • 1
  • 9
  • 17
0

For lower PHP versions like PHP 5.6 you could try:

    date_default_timezone_set('UTC');
    $micro_date = microtime();
    $date_array = explode(" ",$micro_date);
    $date = date("Y-m-d\TH:i:s",$date_array[1]);
    echo $date."." .round( $date_array[0] * 1000)."Z";
Sive.Host
  • 75
  • 1
  • 1