php count remaining hours

Asked

Viewed 455 times

0

What is the best way to calculate the remaining hours of a date? Example:

$date = 2018-02-02;
$calcular_restante = ....;

Missing X Days and X time to get to the day.

What’s the best way to do it?

  • The best way is the one that results in what is most suitable for your application (i.e., if you give more details of how this will be used, help). If it’s only days and hours, it would probably be enough to subtract 2 timestamps and calculate in seconds, not even need to instantiate a Datetime. If you need many fields, the overhead of Datetime + Interval can compensate.

  • @Bacco believes that his answer https://answall.com/a/195690/3635 probably already covers the need, it would be enough to just modify one text or another. The time format for Unix-time would be just a simple and easy-to-adjust detail.

  • @Guilhermenascimento in the "notes" part I even gave the solution already, if you want textual date format. Well noted, I believe it really solves. .

  • 1

    @Bacco marked as dup. Mitchel if you have any other details or something specific whose the response of Bacco does not cover/resolve please inform that I will arrange for reopening.

  • @Guilhermenascimento or, as I add details in the original, so it is more organized.

2 answers

1

You can use the classes Datetime and Dateinterval.

The class Datetime has a method (DateTime::diff) which, passing another date, it will calculate the difference and will return you a Dateinterval informing how much is missing in years, months, days, hours, minutes and seconds to reach a certain nothing.

Example:

<?php

$dataInicial = new DateTime();
$dataFinal = new DateTime("2018-07-13");

$diferenca = $dataInicial->diff($dataFinal);

echo sprintf("Faltam %d anos, %d meses, %d dias, %d horas, %d minutos e %s segundos para {$dataFinal->format('d/m/Y')}",
    $diferenca->y,
    $diferenca->m,
    $diferenca->d,
    $diferenca->h,
    $diferenca->m,
    $diferenca->s);

Demonstration

1

Hello, try this way, you can go adapting the code to get the desired result.

<?php

$data1 = new DateTime();
$data2 = new DateTime('2018-08-20 00:00:00');

echo $data2->diff($data1)->format('Faltam %Y Anos %m Mês, %d dias e %h horas %i minutos');

Browser other questions tagged

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