1

A plain simple task of subtracting time (hours) from a DateTime object leaves me wondering.

I have a DateTime, in my case 2021-03-28 08:45.

I want get back 3 days from that point in time. For that I clone my start date and substract 3 days.

$startMinusDays = (clone $startDate)->sub(new DateInterval('P3D'));

This should in theory be the same as doing:

$startMinusHours = (clone $startDate)->sub(new DateInterval('PT72H'));

However the 2 results are different:

Date - 3 Days : 2021-03-25 08:45:00

Date - 72 Hours: 2021-03-25 07:45:00

This is the full poc code:

Here is a fully working example (https://3v4l.org/j94ae)

<?php
$startDate = date_create_from_format(
    'Y-m-d H:i',
    '2021-03-28 08:45',
    new DateTimeZone("Europe/Madrid")
);

$startMinusDays = (clone $startDate)->sub(new DateInterval('P3D'));
$startMinusHours = (clone $startDate)->sub(new DateInterval('PT72H'));

echo "Date:          : ".$startDate->format('Y-m-d H:i:s');
echo "\n";
echo "Date - 3 Days  : ".$startMinusDays->format('Y-m-d H:i:s');
echo "\n";
echo "Date - 72 Hours: ".$startMinusHours->format('Y-m-d H:i:s');

What am I missing here ? I feel like I'm standing on the hose.

The calculation seems to work for all other times I tried.

cb0
  • 8,415
  • 9
  • 52
  • 80

0 Answers0