ノートDateInterval->日ということは常に正です。したがって、 - >反転を使用します。
/**
* return amount of days between dt1 and dt2
* (how many midnights pass going from dt1 to dt2)
* 0 = same day,
* -1 = dt2 is 1 day before dt1,
* 1 = dt2 is 1 day after dt1, etc.
*
* @param \DateTime $dt1
* @param \DateTime $dt2
* @return int|false
*/
function getNightsBetween(\DateTime $dt1, \DateTime $dt2){
if(!$dt1 || !$dt2){
return false;
}
$dt1->setTime(0,0,0);
$dt2->setTime(0,0,0);
$dti = $dt1->diff($dt2); // DateInterval
return $dti->days * ($dti->invert ? -1 : 1); // nb: ->days always positive
}
使用例:一部のテキストの魔法の
$dt1 = \DateTime::createFromFormat('Y-m-d', '2014-03-03');
$dt2 = \DateTime::createFromFormat('Y-m-d', '2014-02-20');
getNightsBetween($dt1, $dt2); // -11
$dt1 = \DateTime::createFromFormat('Y-m-d H:i:s', '2014-01-01 23:59:59');
$dt2 = \DateTime::createFromFormat('Y-m-d H:i:s', '2014-01-02 00:00:01');
getNightsBetween($dt1, $dt2); // 1 (only 2 seconds later, but still the next day)
$dt1 = \DateTime::createFromFormat('Y-m-d', '2014-04-09');
$dt2 = new \DateTime();
getNightsBetween($dt1, $dt2); // xx (how many days (midnights) passed since I wrote this)
例:
function getRelativeDay(\DateTime $dt2){
if(!$dt2){
return false;
}
$n = getNightsBetween(new \DateTime(), $dt2);
switch($n){
case 0: return "today";
case 1: return "tomorrow";
case -1: return "yesterday";
default:
return $n . (abs($n)>1?"days":"day") . ($n<0?" ago":" from now");
}
}
理由だけではなく、時間なし、日付部分をつかみ、そしてそれからの差異を取得していませんか? – BLaZuRE