nicolae-stelian
nicolae-stelian

Reputation: 344

How to add milliseconds to an Datetime object in php?

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?

Upvotes: 5

Views: 4863

Answers (3)

Prid
Prid

Reputation: 1624

PHP 7.1+

Non string manipulation way to set microseconds is to use DateTime::setTime($h, $m, $s, $µs):

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

$milliseconds = 9;
$ms_in_microseconds = $milliseconds * 1000; // 1000ms in 1 µs

$date->setTime( $dt->format('H'), $dt->format('i'), $dt->format('s'), $ms_in_microseconds );
// in this case, it will run: $date->setTime( 20, 48, 16, 9000 );

A bit tedious, but reliable :)

Upvotes: 0

Sive.Host
Sive.Host

Reputation: 85

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";

Upvotes: 1

jspit
jspit

Reputation: 7703

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"
}

Upvotes: 6

Related Questions