Iter Ator
Iter Ator

Reputation: 9269

How to count the elapsed nights between two dates?

I know, how is it possible to calculate the number of the elapsed days:

$d1 = new DateTime('2010-01-01 12:01');
$d2 = new DateTime('2010-01-03 18:22');

$diff = $d2->diff($d1);

echo $diff->format('%d days');

But how is it possible to count the number of midnights? The 2010-01-01 22:30 and 2010-01-02 06:30 should result one, because there is one midnight between the two datetime values.

Upvotes: 2

Views: 940

Answers (1)

tkausl
tkausl

Reputation: 14269

Easy way: Drop the time and just keep the date:

$d1 = new DateTime('2010-01-01 12:01')->setTime(0, 0, 0);
$d2 = new DateTime('2010-01-03 18:22')->setTime(0, 0, 0);

$diff = $d2->diff($d1);

This will calculate the days from $d1's midnight to $d2's midnight, in this case 2010-01-01 00:00 to 2010-01-03 00:00

Upvotes: 3

Related Questions