Remove an hour with minutes or not from a date

Asked

Viewed 27 times

0

I have the following code:

<?php

  //batidas do controle de ponto de um x colaborador
  $d1 = new DateTime('2021-08-06 12:00:00');
  $d2 = new DateTime('2021-08-06 15:00:00');
  $d3 = new DateTime('2021-08-06 15:30:00');
  $d4 = new DateTime('2021-08-06 17:00:00');
  $d5 = new DateTime('2021-08-06 17:30:00');
  $d6 = new DateTime('2021-08-06 21:00:00');

  $i1 = $d1->diff($d2);
  $i2 = $d2->diff($d3);

  $remover = new DateInterval("T1H");

  echo $i1->format('%H:%I') . "<br />";
  echo $i2->format('%H:%I') . "<br />";

  print_r($i1->sub($remover));

Then you make the following mistake:

"FATAL ERROR Uncaught Exception: Dateinterval::__Construct(): Unknown or bad format (T1H) in /var/www/html/index.php74(3) : Eval()’d code:13 Stack trace: #0 /var/www/html/index.php74(3) : Eval()’d code(13): Dateinterval->__Construct('T1H') #1 /var/www/html/index.php74(3): Eval() #2 {main} thrown on line number 13"

But I don’t know what’s wrong? I would like to subtract an hour from the variable $i1 or put as parameter in the class DateInterval() an hour with seconds or not dynamically?

1 answer

0


According to the documentation, the builder of DateInterval accepts strings in the format described by ISO 8601 standard.

And according to this rule, durations at all times begin with the letter "P". Therefore, the one hour interval should be written as PT1H:

$remover = new DateInterval("PT1H");

However, this still does not solve the problem of subtracting a DateInterval of another. The method sub is only available for DateTime (to subtract a duration from a date).

However, $i1 is a duration (a DateInterval), for he is the result of diff (the difference between two dates is a duration - understand better by reading here). And to subtract two DateInterval's you would have to do manually. Unfortunately you have nothing ready, but you can base yourself, for example, in this code here:

// subtrai dois DateInterval's e retorna outro com o resultado
function subtractDateIntervals($intervalOne, $intervalTwo) {
    $keys = ["y", "m", "d", "h", "i", "s"];

    $intervalArrayOne = array_intersect_key((array)$intervalOne, array_flip($keys));
    $intervalArrayTwo = array_intersect_key((array)$intervalTwo, array_flip($keys));

    $result = array_map(function($v1, $v2){
        return abs($v1 - $v2);
    }, $intervalArrayOne, $intervalArrayTwo);

    return new DateInterval(vsprintf("P%dY%dM%dDT%dH%dM%dS", $result));
}

print_r(subtractDateIntervals($i1, $remover));

Browser other questions tagged

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