Reputation: 732
So I'm trying to calculate the number of days offset one date is from another. Currently I am using:
$now = new DateTime();
$dateToCompare = new DateTime("<filled from DB>");
$diff = $now->diff($dateToCompare);
echo $diff->format("%R%a");
What I'm finding is that this compares the dates and gives the offset relative to 24 hour periods, not calendar days.
For example, these dates have a day offset of 0 (where I would expect it to be 1):
2012-10-11 19:27:04 and 2012-10-12 06:50:00
Am I using this function correctly? I would expect this to be an offset of 1; however after lots of debugging, I have found that this is the source of the discrepancy I am actually seeing in the date offsets.
(The timezone is being set also as suggested by PHP)
Thanks for your help in advance!
Upvotes: 2
Views: 1686
Reputation: 5101
Try using DateTime::createFromFormat using just month, day, and year to create your objects.
Maybe try the following untested code:
$now = DateTime::createFromFormat('Y-m-d', date('Y-m-d')); // Note that if no timestamp is given, it uses the current time instead of 12am
$dateToCompare = DateTime::createFromFormat('Y-m-d', "<filled from DB>"); //match format of db datetime
$diff = $now->diff($dateToCompare);
echo $diff->format("%R%a");
Upvotes: 3
Reputation: 1
Just use year, month, and date:
$now = strtotime(Date("Y-m-d", strtotime("2012-10-12 06:50:00")));
$pre = strtotime(Date("Y-m-d", strtotime("2012-10-11 19:27:04")));
var_dump(($now-$pre)/86400);
In my environment DateTime
does not work.
Upvotes: 0
Reputation: 2136
If youre looking for a simple way you can try this
$date1 = strtotime("2012-10-11 19:27:04");
$date2 = strtotime("2012-10-12 06:50:00");
$diff = ($date1-$date2);
echo date('j',$diff)." days";
The output is 31 days
You can replace the 'j' with the supported date format characters here http://php.net/manual/en/function.date.php
Upvotes: 1