user1022585
user1022585

Reputation: 13651

php add to time

Why doesn't $now2 work?

$now = date('Y-m-d H:i:s', time()); 
$now2 = date("Y-m-d H:i:s", strtotime( "$now + 0.5 secs"));

Or how can I get it to work?

Upvotes: 0

Views: 141

Answers (3)

Andre Lackmann
Andre Lackmann

Reputation: 666

time() returns the number of seconds since the epoch. It doesn't know anything about fractions of a second. You'll need to use microtime() if you need this level of accuracy (see: http://php.net/manual/en/function.microtime.php)

Edit: You of course can't use microtime in the date() formatting, so you need to do a calculation prior and then use it. Similar to:

$now = microtime(true);
$newtime = $now + 0.5;

echo date("Y-m-d H:i:s", round($newtime,0) );

Depending on your requirements, you may prefer to use a different function than round() to make $newtime and integer again suitable for formatting with date()

Upvotes: 2

Baba
Baba

Reputation: 95101

The reason its now working is because PHP does not recognize 0.5 secs has valid

0.5 secs is not a valid date format .. but it is a valid microtime

Try

$now = date('Y-m-d H:i:s', time());
var_dump(strtotime( "$now + 1 secs"));

Output

int 1334188908

Upvotes: 2

staticsan
staticsan

Reputation: 30555

The resolution of a Unix timestamp (which is what time() returns) is only 1 second. So you can't add half of a second to it.

Upvotes: 1

Related Questions