0

I have time :

$t='2019-03-13 11:16:29'

How can i minus one milisecond from it ?

For minus minute i use it:

date('Y-m-d H:i:s', strtotime("-1 minute", strtotime($t)));
  • 2
    And what results are expected for such operation? You don't define miliseconds in your time (2019-03-13 11:16:29), so they are 0? So subtracting 1 milisecond is the same as subtracting one second? – Krzysiek Dróżdż Mar 14 '19 at 08:15
  • Possible duplicate of [How to subtract microtime and display date with milliseconds in php?](https://stackoverflow.com/questions/9371457/how-to-subtract-microtime-and-display-date-with-milliseconds-in-php) – Robson Mar 14 '19 at 08:29

2 Answers2

2

Since PHP 7.0.0 there 's a format called "v" for milliseconds. For all formats please have a look at the manual. With this in mind you can easily display milliseconds.

$date = $date = new DateTime('2019-03-13 11:16:29');
echo $date->format('v') . PHP_EOL;

$date->modify('-1 millisecond');
echo $date->format('v');

Since we create a DateTime object without milliseconds, the result will be 999, because in initialization the DateTime objects milliseconds is 000.

Another example with milliseconds would be like the following code.

$date = new DateTime('2019-03-13 11:16:29.123456');
echo $date->format('Y-m-d H:i:s.u') . PHP_EOL;
$date->modify('-1 millisecond');

echo $date->format('Y-m-d H:i:s.u');

The result would be ...

2019-03-13 11:16:29.123456 
2019-03-13 11:16:29.122456

As you can see there was subtracted exactly one millisecond.

jeprubio
  • 17,312
  • 5
  • 45
  • 56
Marcel
  • 4,854
  • 1
  • 14
  • 24
1

strtotime function returns a timestamp, which is the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

So you won't get any milliseconds from strtotime. You can check it writing:

echo date('Y-m-d H:i:s.u', strtotime('2019-03-13 11:16:29'));

It should print this:

2019-03-13 11:16:29.000000

It means that if you subtract a millisecond, then it will be always the same as subtracting all second...

But you can do it like so:

date('Y-m-d H:i:s', strtotime('-1 millisecond', strtotime($t)));

Although it will still return the result without milliseconds. So this code:

$t = strtotime('2019-03-13 11:16:29');
echo date('Y-m-d H:i:s.u', $t); echo "\n";
echo date('Y-m-d H:i:s.u', strtotime('-1 second', $t)); echo "\n";
echo date('Y-m-d H:i:s.u', strtotime('-1 millisecond', $t));

Will print this:

2019-03-13 11:16:29.000000
2019-03-13 11:16:28.000000
2019-03-13 11:16:28.000000