问题
I know there a lot of questions and answers of this already, but unfortunately I think my situation may be unique? For some reason, the time-change seems to be making the day calculate as one day less than it should be calculating.
Here is my PHP that I was using and it was working great, until it started to overlap a start and end date that was BEFORE daylight savings, and AFTER daylight savings, respectively (FYI, this is a recent issue, since daylight savings time starts this weekend!):
//$lastDate and $firstDate are 2 unix timestamps with valid month, day, and year values.
//The times are irrelevant at this point, they are only meant to represent a day.
//I start by making sure these have the same time values.
$lastDate = mktime(23, 59, 59, date("m", $lastDate), date("j", $lastDate), date("Y", $lastDate));
$firstDate = mktime(23, 59, 59, date("m", $firstDate), date("j", $firstDate), date("Y", $firstDate));
//Then calculate the total number of days in between.
$totalDays = abs(floor(($firstDate - $lastDate)/(60*60*24)));
So again, to be clear, the above works if i'm not overlapping the daylight savings time change...
For reference:
How to find the dates between two specified date?
Actual days between two unix timestamps in PHP
Finding days between 2 unix timestamps in php
And, I'm still on PHP 5.2 right now.
EDIT/UPDATE:
I've found the following on this links:
How to find the dates between two specified date?
and
How to calculate the the interval between 2 unix timestamps in php WITHOUT dividing by 86400 (60*60*24)
//$lastDate and $firstDate are 2 unix timestamps with valid month, day, and year values.
//The times are irrelevant at this point, they are only meant to represent a day.
//I start by making sure these have the same time values.
$lastDate = mktime(10, 00, 00, date("m", $lastDate), date("j", $lastDate), date("Y", $lastDate));
$firstDate = mktime(10, 00, 00, date("m", $firstDate), date("j", $firstDate), date("Y", $firstDate));
//Then calculate the total number of days in between.
$totalDays = floor($firstDate / 86400) - floor($lastDate/ 86400);
And it seems to work right now for the crossover of DST. Anyone see any issues with this?
回答1:
Are you running on PHP 5.3+? A DateInterval
fits the problem nicely.
http://www.php.net/manual/en/datetime.diff.php
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
来源:https://stackoverflow.com/questions/15302469/problems-with-finding-the-days-between-two-unix-timestamps