以天为单位获取PHP日期时间差异,将午夜视为一天的变化

时间:2013-08-07 11:47:34

标签: php date datetime dateinterval

在两个PHP DateTimes之间获取差异的最简单方法是什么,将午夜视为一天的变化(就像DATEDIFF(DAY) SQL函数那样)?

例如,在今天的13:00和明天的12:00之间,我应该得到1(天),即使间隔时间少于24小时。

$date1 = new DateTime("2013-08-07 13:00:00");
$date2 = new DateTime("2013-08-08 12:00:00");
echo $date1->diff($date2)->days; // 0

5 个答案:

答案 0 :(得分:47)

您可以忽略日期字符串的时间部分

$date1 = new DateTime(date('Y-m-d', strtotime("2013-08-07 13:00:00")));
$date2 = new DateTime(date('Y-m-d', strtotime("2013-08-08 12:00:00")));
echo $date1->diff($date2)->days; // 1

答案 1 :(得分:7)

这是一个简单的解决方案,可以消除时间或将其设置为00:00:00,这应该始终能够为您提供所需的结果:

$date1 = new DateTime("2013-08-07");
$date2 = new DateTime("2013-08-08");
echo $date1->diff($date2)->days;

$date1 = new DateTime("2013-08-07 00:00:00");
$date2 = new DateTime("2013-08-08 00:00:00");
echo $date1->diff($date2)->days;

时间在这里并不重要

答案 2 :(得分:6)

请注意,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");
    }
}

答案 3 :(得分:2)

$date1 = new DateTime("2013-08-07 13:00:00");
$date2 = new DateTime("2013-08-08 12:00:00");
  1. 在DateTime的对象中放置时间:
$date1->setTime(0, 0, 0);
$date2->setTime(0, 0, 0);
  1. 获得不同的适应对象:
echo $date1->diff($date2)->days;

答案 4 :(得分:-2)

这个例子可以帮助你:

   $date1 = date_create($d1);
$date2 = date_create($d2);
//$FromFullDateTime=$from.$FromTime;

$date1_month = date_format($date1, 'd');
$date2_month = date_format($date2, 'd');
$dif = $date2_month - $date1_month;