Skip to content
Advertisement

DateTime(‘now’) not modified after sleep()

I have following code

$now = new DateTime('now');
$string1 = $now->format('Y-m-d H:i:s');
sleep(5);
$now->modify('now');        
$string2 = $now->format('Y-m-d H:i:s');
sleep(10);
$now->modify('now');        
$string3 = $now->format('Y-m-d H:i:s');
echo $string1 . '<br>';
echo $string2 . '<br>';
echo $string3 . '<br>';

I expected to get each line different time. surprisingly the output is like this.

2020-11-27 17:35:05
2020-11-27 17:35:05
2020-11-27 17:35:05

I suspected it is the buffer flush problem so added $string variables but it is still the same. Can anyone explain why it happens? Thanks.

Regards, Marcin

Advertisement

Answer

The ‘now’ parameter is simply ignored. This is also documented in the PHP manual. When creating with

$now = date_create(); // or new DateTime;

It doesn’t matter whether the parameter is “now” or none.

My recommendation: Always recreate the current time with new DateTime.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement