Molfar
Molfar

Reputation: 1501

Modify DateTime object

I create an object

$date = new DateTime();

It is set to current date 2011-04-01 21:43:40. I try the following

$date->modify('midnight');

I expect the object to set to 2011-04-01 00:00:00. But nothing happened. Object hadn't beed modified, and continue to have a 2011-04-01 21:43:40 date. I just want to reset the time to midnight (00:00:oo).

Upvotes: 3

Views: 7345

Answers (5)

user3913971
user3913971

Reputation: 13

Solved using

$date = new DateTime(date('Y-m-d H:i:s', strtotime('today midnight')));
echo $date->format('Y-m-d H:i:s');

Upvotes: 0

VladoM
VladoM

Reputation: 64

I had the same problem! However the returned date was correct, so what I did is:

@$date->modify('midnight');

Upvotes: 0

Jacques
Jacques

Reputation: 1

Doctrine checks if the DateTime object has changed its reference. Modifying an object doesn’t change the reference, so for doctrine, this is not a change. Use new \DateTime('midnight') instead.

Upvotes: 0

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 30013

http://codepad.org/w5RAF0Lh

This piece of code (with midnight) will not work without date.timezone setting

UPDATE: this piece of code requires PHP 5.3.6 to work correctly. In previous versions DateTime::modify('midnight') didn't work

Upvotes: 2

macguru2000
macguru2000

Reputation: 2132

Got a few questions, perhaps the will help illuminate the problem...

Is a timezone set in your php.ini file?

After you create the new DateTime() object are you using var_dump() or some other function to view its parameters and get the set date?

Have you tried and been successful passing other date and time formats into the modify method?

Upvotes: 0

Related Questions