Subtract PHP date and time

Asked

Viewed 246 times

-1

I looked it up online and couldn’t find anything to help me solve this problem. I need to do the following, get a date/time informed by the system and decrease it by 5 hours. Example:

2019-08-29 02:40

this date and time were informed by the system and I need to take 5 hours from this date, except 5 hours should stay: 2018-08-28 21:40, someone could help me?

  • https://www.php.net/manual/en/datetime.sub.php

  • Is basically that, but instead of add, use sub, and in cases where '+X hours', swap for '-X hours'

1 answer

2


Can resilver this with the objects of Datetime and Dateinterval.

Following example:

<?php
// Intervalo de 5 horas.
$Intervalo = new DateInterval("PT5H");
// P = Periodo que no seu caso não se aplica, pois manipula dias meses e anos
// T = Representação de tempo em horas.
// 5 = O tamanho do intervalo;
// H = Horas

// Data do sistema.
$data = new DateTime();

// Testar o objeto.
print("<pre>");
print("A data atual é: <br>");
print_r($data);
print("</pre>");

// Aplicando a remoçlão de 5 horas.
$data->sub($Intervalo);

// Testar o objeto.
print("<pre>");
print("A nova data é: <br>");
print_r($data);
print("</pre>");

The exit from execution shall be:

A data atual é: 
DateTime Object
(
    [date] => 2019-08-29 19:53:15.776538
    [timezone_type] => 3
    [timezone] => America/Sao_Paulo
)

A nova data é: 
DateTime Object
(
    [date] => 2019-08-29 14:53:15.776538
    [timezone_type] => 3
    [timezone] => America/Sao_Paulo
)

I hope it helps...

Browser other questions tagged

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