Rikard
Rikard

Reputation: 7805

Change DateTime() offset in PHP

Is it possible in PHP to change the DateTime() to a custom time difference. Like adding it 20 min and everytime I call new DateTime() I would get those extra 20 min to the current date.

I thought about __construct() but didn't see how to fix it.

I can use a function of course, but just curious to know if its possible to change the prototype new DateTime()

Upvotes: 1

Views: 231

Answers (3)

vascowhite
vascowhite

Reputation: 18440

You can do this all in one line:-

$date = (new \DateTime())->add(new \DateInterval('PT20M'));

That would be my preferred way of doing it.

See it working in PHP >= 5.3

Upvotes: 1

SenseException
SenseException

Reputation: 1075

Ilia Rostovtsev's answer is a good one for achieving your goal. Alternatively you can also use the DateInterval class with DateTime::add(). Personally, I prefer that one because you don't need to know how strings need to look like while DateInterval uses a standard like P1d for a day.

I wouldn't use inheritance to get a DateTime class including your wished behaviour. Instead you can create some kind of factory which contains Ilia's code (and every other code that is part for the object creation). The interval can be added as parameter. Your added interval, your 20 minutes should be stored in a constant in case you need to change that interval in the future while technically being able to use other intervals than 20 minutes.

Upvotes: 1

Ilia Ross
Ilia Ross

Reputation: 13404

Yes, it's possible:

$date = new DateTime();
$date->modify("+20 minutes"); //or whatever value you want

Example online

Upvotes: 2

Related Questions