Subtract one hour from Current time

Asked

Viewed 2,194 times

0

How do I subtract an example time:

<?php
$hora = "00:12:00"
eco $hora;
?>

How do I get like this :

11:12:00

4 answers

2

$hora = "00:12:00";
echo date("g:i:s", srttotime("-1 Hour", strtotime($hora)));

1


One option is to use the method sub to subtract an interval using the DateInterval in which PT1H represents 1 hour. See:

$date = new DateTime('00:12:00');
$date->sub(new DateInterval('PT1H'));
echo $date->format('h:i:s') . "\n";

Behold working at Ideone.

0

I believe that this is not the appropriate way to do this, but I created this function for such action:

    <?php
    function menosUmaHora($string) {
        $hora = explode(':', $string);//Cria uma array com 3 posições: 0 hora, 1 minuto, 2 segundo
        $hora[0] = (int) $hora[0]; //converte de string para inteiro
        $hora[1] = (int) $hora[1]; //converte de string para inteiro
        $hora[2] = (int) $hora[2]; //converte de string para inteiro
        if ($hora[0] <= 0) { //Verifica se o valor da posição hora é menor ou igual a 0
            $hora[0] = 11; //Se sim, posição hora agora é 11
        } else {
            $hora[0] --; //Se não, posição hora terá 1 subtraido
        }
        return implode(':', $hora);//Monta a string em ordem hh:mm:ss e retorna
    }

    $string = "00:12:00";
    echo "Old hour: " . $string . '<br>';
    echo "New hour: " . menosUmaHora($string);
?>

-1

Returns one hour before the current date and time.

date('d/m/Y H:i', strtotime('-1 hour', strtotime(date('Y-m-d H:i:s'))));

Browser other questions tagged

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