Add an hour to the current time

Asked

Viewed 502 times

3

I’m trying to record the current system time.

For example the current date will be 01-08-2019 10:34:44 and I wanted that same date, but add another hour, IE, would be 01-08-2019 11:34:44.

$data_pagamento = date('Y-m-d H:i:s');

3 answers

9


You can use the DateTime and add to 1 hour with modify.

$date = new DateTime();
$date->modify('+1 hour');

6

An alternative is to use strtotime, that accepts some special formats, among them +x hours to add hours:

$data_pagamento = date('Y-m-d H:i:s' , strtotime('+1 hours'));

In case, the string could be both '+1 hour' how much '+1 hours'.


You can also use DateTime, that has the method add (which in turn receives a DateInterval with the duration to be added):

$now = new DateTime(); // data/hora atual
$now->add(new DateInterval('PT1H')); // somar 1 hora
$data_pagamento = $now->format('Y-m-d H:i:s');

In that case, the DateInterval receives a duration in ISO 8601 format (PT1H is equivalent to a duration of 1 hour).

Remembering that despite the name, the function date returns a string containing the date/time in the given format. To obtain this same string with DateTime, it is necessary to use the method format.

Note: the above code would serve to add hours to any DateTime. But if you just want "the date/time current another 1 hour", it is also possible to use the same format as strtotime accepted:

$now = new DateTime('+1 hours'); // data/hora atual + 1 hora
$data_pagamento = $now->format('Y-m-d H:i:s');

Generalizing to an arbitrary amount of hours:

$qtd_horas = 5;

// com DateTime
$now = new DateTime();
$now->add(new DateInterval("PT{$qtd_horas}H"));
$data_pagamento = $now->format('Y-m-d H:i:s');
// ou
$now = new DateTime("+{$qtd_horas} hours");
$data_pagamento = $now->format('Y-m-d H:i:s');

// com strtotime
$data_pagamento = date('Y-m-d H:i:s' , strtotime("+{$qtd_horas} hours"));

Finally, it is worth noting that strtotime (or the method modify, as suggested in answer from Rafael) is, in my opinion, simpler to understand (the semantics is very clear as to what is happening: I am adding X hours).

The alternative with DateInterval can be confusing for those unfamiliar with the ISO 8601 format. But once you know it (and it’s not that complicated), also has a very clear semantics.

Adding up "magic" and "arbitrary" numbers like 3600, although it works, is the least simple to understand (since we have to stop and think about where that number comes from). Although "obvious" to those who are accustomed to such calculations, I still think the other alternatives (strtotime, add and modify) are better.

2

solved, I managed to solve as follows.

$data_pagamento = date('Y-m-d H:i:s' , time()+3600);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.