Date/Time 函数
在线手册:中文 英文
PHP手册

date_diff

(PHP 5 >= 5.3.0)

date_diff别名 DateTime::diff()

说明

此函数是该函数的别名: DateTime::diff()


Date/Time 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 别名 DateTime::diff

用户评论:

holdoffhunger at gmail dot com (28-Mar-2012 05:37)

I wanted to have a formatted time difference function that worked with two time() integer results and formatted the results, such as "X Years, Y Months, Z Weeks, etc.."  The following is that function, and it's designed to be modifiable, so you could easily cut out the standard Years / Months / Weeks / Days / Hours / Minutes / Seconds Format, and go to whatever format you prefer in whatever order you prefer.

<?php

           
// Author: holdoffhunger@gmail.com

        // Define Input
        // --------------------------------------

            // Example Time Difference
       
   
$start_time_for_conversion = 0;
   
$end_time_for_conversion = 123456;
   
   
$difference_of_times = $end_time_for_conversion - $start_time_for_conversion;
   
   
$time_difference_string = "";
   
    for(
$i_make_time = 6; $i_make_time > 0; $i_make_time--)
    {
        switch(
$i_make_time)
        {
               
// Handle Minutes
                // ........................
               
           
case '1';
               
$unit_title = "Minute(s)";
               
$unit_size = 60;
                break;
               
               
// Handle Hours
                // ........................
               
           
case '2';
               
$unit_title = "Hour(s)";
               
$unit_size = 3600;
                break;
               
               
// Handle Days
                // ........................
               
           
case '3';
               
$unit_title = "Day(s)";
               
$unit_size = 86400;
                break;
               
               
// Handle Weeks
                // ........................
               
           
case '4';
               
$unit_title = "Week(s)";
               
$unit_size = 604800;
                break;
               
               
// Handle Months (31 Days)
                // ........................
               
           
case '5';
               
$unit_title = "Month(s)";
               
$unit_size = 2678400;
                break;
               
               
// Handle Years (365 Days)
                // ........................
               
           
case '6';
               
$unit_title = "Year(s)";
               
$unit_size = 31536000;
                break;
        }
   
        if(
$difference_of_times > ($unit_size - 1))
        {
           
$modulus_for_time_difference = $difference_of_times % $unit_size;
           
$seconds_for_current_unit = $difference_of_times - $modulus_for_time_difference;
           
$units_calculated = $seconds_for_current_unit / $unit_size;
           
$difference_of_times = $modulus_for_time_difference;
   
           
$time_difference_string .= "$units_calculated $unit_title, ";
        }
    }
   
       
// Handle Seconds
        // ........................
   
   
$time_difference_string .= "$difference_of_times Second(s)";

           
// Example Result: "1 Day(s), 10 Hour(s), 17 Minute(s), 36 Second(s)"

?>

One other example: 123456789 = "3 Year(s), 10 Month(s), 3 Week(s), 2 Day(s), 21 Hour(s), 33 Minute(s), 9 Second(s)"

maniarpratik at gmail dot com (20-Feb-2012 06:07)

This function will return count of sunday between inputed dates.

<?php
function CountSunday($from,$to)
{
   
$from=date('d-m-Y',strtotime($from));
$to=date('d-m-Y',strtotime($to));
$cnt=0;
$nodays=(strtotime($to) - strtotime($from))/ (60 * 60 * 24); //it will count no. of days
$nodays=$nodays+1;
           for(
$i=0;$i<$nodays;$i++) 
            {      
               
$p=0;
            list(
$d, $m, $y) = explode("-",$from);
           
$datetime = strtotime("$d-$m-$y");           
           
$nextday = date('d-m-Y',strtotime("+1 day", $datetime));  //this will add one day in from date (from date + 1)
           
if($i==0)                           
               
$p=date('w',strtotime($from));                           
            else
               
$p=date('w',strtotime($nextday));
           
            if(
$p==0)            // check whethere value is 0 then its sunday
               
$cnt++;                                //count variable of sunday                       
            
$from=$nextday;         
            
$p++;           
            }            
  return
$cnt;
}
?>

Toine (contact at toine dot pro) (26-Aug-2011 03:22)

This is a very simple function to calculate the difference between two timestamp values.
<?php
function diff($start,$end = false) {
   
/*
    * For this function, i have used the native functions of PHP. It calculates the difference between two timestamp.
    *
    * Author: Toine
    *
    * I provide more details and more function on my website
    */

    // Checks $start and $end format (timestamp only for more simplicity and portability)
   
if(!$end) { $end = time(); }
    if(!
is_numeric($start) || !is_numeric($end)) { return false; }
   
// Convert $start and $end into EN format (ISO 8601)
   
$start  = date('Y-m-d H:i:s',$start);
   
$end    = date('Y-m-d H:i:s',$end);
   
$d_start    = new DateTime($start);
   
$d_end      = new DateTime($end);
   
$diff = $d_start->diff($d_end);
   
// return all data
   
$this->year    = $diff->format('%y');
   
$this->month    = $diff->format('%m');
   
$this->day      = $diff->format('%d');
   
$this->hour     = $diff->format('%h');
   
$this->min      = $diff->format('%i');
   
$this->sec      = $diff->format('%s');
    return
true;
}

/*
 * How use it?
 *
 * Call your php class (myClass for this example) and use the function :
*/
$start  = strtotime('1985/02/09 13:54:17');
$end    = strtotime('2012/12/12 17:30:21');
$myClass = new myClass();
$myClass->Diff($start,$end);
// Display result
echo 'Year: '.$myClass->Year;
echo
'<br />Month: '.$myClass->Month;
echo
'<br />Day: '.$myClass->Day;
echo
'<br />Hour: '.$myClass->Hour;
echo
'<br />Min: '.$myClass->Min;
echo
'<br />Sec: '.$myClass->Sec;
// Display only month for all duration
$month = ($myClass->Year * 12) + $myClass->Month;
echo
'<br />Total month: '.$month;
// if you want you can use this function without $end value :
$myClass->Diff($start);
// Automatically the end is the current timestamp
?>

vglebov at gmail dot com (26-May-2011 07:59)

Get the difference between the dates without days off

<?php
function get_date_diff($date1, $date2) {
 
$holidays = 0;
  for (
$day = $date2; $day < $date1; $day += 24 * 3600) {
   
$day_of_week = date('N', $day);
    if(
$day_of_week > 5) {
     
$holidays++;
    }
  }
  return
$date1 - $date2 - $holidays * 24 * 3600;
}

function
test_get_date_diff()
{
 
$datas = array(
    array(
'Fri 20 May 2011 14:00:00', 'Fri 20 May 2011 13:00:00', 1 * 3600),
    array(
'Sat 21 May 2011 15:00:00', 'Fri 20 May 2011 13:00:00', 2 * 3600),
    array(
'Sun 22 May 2011 16:00:00', 'Fri 20 May 2011 13:00:00', 3 * 3600),
    array(
'Mon 23 May 2011 14:00:00', 'Fri 20 May 2011 13:00:00', 25 * 3600),
    array(
'Fri 27 May 2011 13:00:00', 'Fri 13 May 2011 13:00:00', 24 * 10 * 3600),
  );
  foreach (
$datas as &$data) {
   
$actual = get_date_diff(strtotime($data[0]), strtotime($data[1]));
    if (
$actual != $data[2]) {
      echo
"Test for get_date_diff faled expected {$data[2]} but was {$actual}, date1: {$data[0]}, date2: {$data[1]}.<br>";
    }
  }
}
test_get_date_diff($data);
?>

alessandro dot faustini at nixylab dot it (03-Feb-2011 06:08)

In versions < 5.3.0 I simply use this form for calculate the number of days

<?php
$today
= strtotime("2011-02-03 00:00:00");
$myBirthDate = strtotime("1964-10-30 00:00:00");
printf("I'm %d days old.", round(abs($today-$myBirthDate)/60/60/24));
?>

kshegunov at gmail dot com (10-Jan-2011 05:26)

Here is how I solved the problem of missing date_diff function with php versions below 5.3.0
The function accepts two dates in string format (recognized by strtotime() hopefully), and returns the date difference in an array with the years as first element, respectively months as second, and days as last element.
It should be working in all cases, and seems to behave properly when moving through February.

<?php
       
function dateDifference($startDate, $endDate)
        {
           
$startDate = strtotime($startDate);
           
$endDate = strtotime($endDate);
            if (
$startDate === false || $startDate < 0 || $endDate === false || $endDate < 0 || $startDate > $endDate)
                return
false;
               
           
$years = date('Y', $endDate) - date('Y', $startDate);
           
           
$endMonth = date('m', $endDate);
           
$startMonth = date('m', $startDate);
           
           
// Calculate months
           
$months = $endMonth - $startMonth;
            if (
$months <= 0)  {
               
$months += 12;
               
$years--;
            }
            if (
$years < 0)
                return
false;
           
           
// Calculate the days
                       
$offsets = array();
                        if (
$years > 0)
                           
$offsets[] = $years . (($years == 1) ? ' year' : ' years');
                        if (
$months > 0)
                           
$offsets[] = $months . (($months == 1) ? ' month' : ' months');
                       
$offsets = count($offsets) > 0 ? '+' . implode(' ', $offsets) : 'now';

                       
$days = $endDate - strtotime($offsets, $startDate);
                       
$days = date('z', $days);   
                       
            return array(
$years, $months, $days);
        }
?>

Sven Obser (16-Sep-2010 08:40)

Here is an incomplete workaround for PHP < 5.3.0
<?php
/**
 * Workaround for PHP < 5.3.0
 */
if(!function_exists('date_diff')) {
    class
DateInterval {
        public
$y;
        public
$m;
        public
$d;
        public
$h;
        public
$i;
        public
$s;
        public
$invert;
       
        public function
format($format) {
           
$format = str_replace('%R%y', ($this->invert ? '-' : '+') . $this->y, $format);
           
$format = str_replace('%R%m', ($this->invert ? '-' : '+') . $this->m, $format);
           
$format = str_replace('%R%d', ($this->invert ? '-' : '+') . $this->d, $format);
           
$format = str_replace('%R%h', ($this->invert ? '-' : '+') . $this->h, $format);
           
$format = str_replace('%R%i', ($this->invert ? '-' : '+') . $this->i, $format);
           
$format = str_replace('%R%s', ($this->invert ? '-' : '+') . $this->s, $format);
           
           
$format = str_replace('%y', $this->y, $format);
           
$format = str_replace('%m', $this->m, $format);
           
$format = str_replace('%d', $this->d, $format);
           
$format = str_replace('%h', $this->h, $format);
           
$format = str_replace('%i', $this->i, $format);
           
$format = str_replace('%s', $this->s, $format);
           
            return
$format;
        }
    }

    function
date_diff(DateTime $date1, DateTime $date2) {
       
$diff = new DateInterval();
        if(
$date1 > $date2) {
           
$tmp = $date1;
           
$date1 = $date2;
           
$date2 = $tmp;
           
$diff->invert = true;
        }
       
       
$diff->y = ((int) $date2->format('Y')) - ((int) $date1->format('Y'));
       
$diff->m = ((int) $date2->format('n')) - ((int) $date1->format('n'));
        if(
$diff->m < 0) {
           
$diff->y -= 1;
           
$diff->m = $diff->m + 12;
        }
       
$diff->d = ((int) $date2->format('j')) - ((int) $date1->format('j'));
        if(
$diff->d < 0) {
           
$diff->m -= 1;
           
$diff->d = $diff->d + ((int) $date1->format('t'));
        }
       
$diff->h = ((int) $date2->format('G')) - ((int) $date1->format('G'));
        if(
$diff->h < 0) {
           
$diff->d -= 1;
           
$diff->h = $diff->h + 24;
        }
       
$diff->i = ((int) $date2->format('i')) - ((int) $date1->format('i'));
        if(
$diff->i < 0) {
           
$diff->h -= 1;
           
$diff->i = $diff->i + 60;
        }
       
$diff->s = ((int) $date2->format('s')) - ((int) $date1->format('s'));
        if(
$diff->s < 0) {
           
$diff->i -= 1;
           
$diff->s = $diff->s + 60;
        }
       
        return
$diff;
    }
}
?>

Sergio Abreu (26-Jun-2010 03:22)

<?php
/*
 * A mathematical decimal difference between two informed dates
 *
 * Author: Sergio Abreu
 * Website: http://sites.sitesbr.net
 *
 * Features:
 * Automatic conversion on dates informed as string.
 * Possibility of absolute values (always +) or relative (-/+)
*/

function s_datediff( $str_interval, $dt_menor, $dt_maior, $relative=false){

       if(
is_string( $dt_menor)) $dt_menor = date_create( $dt_menor);
       if(
is_string( $dt_maior)) $dt_maior = date_create( $dt_maior);

      
$diff = date_diff( $dt_menor, $dt_maior, ! $relative);
      
       switch(
$str_interval){
           case
"y":
              
$total = $diff->y + $diff->m / 12 + $diff->d / 365.25; break;
           case
"m":
              
$total= $diff->y * 12 + $diff->m + $diff->d/30 + $diff->h / 24;
               break;
           case
"d":
              
$total = $diff->y * 365.25 + $diff->m * 30 + $diff->d + $diff->h/24 + $diff->i / 60;
               break;
           case
"h":
              
$total = ($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h + $diff->i/60;
               break;
           case
"i":
              
$total = (($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h) * 60 + $diff->i + $diff->s/60;
               break;
           case
"s":
              
$total = ((($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h) * 60 + $diff->i)*60 + $diff->s;
               break;
          }
       if(
$diff->invert)
               return -
1 * $total;
       else    return
$total;
   }

/* Enjoy and feedback me ;-) */
?>

Flavio Tubino (27-May-2010 01:37)

This is a very simple function to calculate the difference between two datetime values, returning the result in seconds. To convert to minutes, just divide the result by 60. In hours, by 3600 and so on.

Enjoy.

<?php
function time_diff($dt1,$dt2){
   
$y1 = substr($dt1,0,4);
   
$m1 = substr($dt1,5,2);
   
$d1 = substr($dt1,8,2);
   
$h1 = substr($dt1,11,2);
   
$i1 = substr($dt1,14,2);
   
$s1 = substr($dt1,17,2);   

   
$y2 = substr($dt2,0,4);
   
$m2 = substr($dt2,5,2);
   
$d2 = substr($dt2,8,2);
   
$h2 = substr($dt2,11,2);
   
$i2 = substr($dt2,14,2);
   
$s2 = substr($dt2,17,2);   

   
$r1=date('U',mktime($h1,$i1,$s1,$m1,$d1,$y1));
   
$r2=date('U',mktime($h2,$i2,$s2,$m2,$d2,$y2));
    return (
$r1-$r2);

}
?>

eugene at ultimatecms dot co dot za (17-Mar-2010 07:58)

This function calculates the difference up to the second.

<?php

function date_diff($start, $end="NOW")
{
       
$sdate = strtotime($start);
       
$edate = strtotime($end);

       
$time = $edate - $sdate;
        if(
$time>=0 && $time<=59) {
               
// Seconds
               
$timeshift = $time.' seconds ';

        } elseif(
$time>=60 && $time<=3599) {
               
// Minutes + Seconds
               
$pmin = ($edate - $sdate) / 60;
               
$premin = explode('.', $pmin);
               
               
$presec = $pmin-$premin[0];
               
$sec = $presec*60;
               
               
$timeshift = $premin[0].' min '.round($sec,0).' sec ';

        } elseif(
$time>=3600 && $time<=86399) {
               
// Hours + Minutes
               
$phour = ($edate - $sdate) / 3600;
               
$prehour = explode('.',$phour);
               
               
$premin = $phour-$prehour[0];
               
$min = explode('.',$premin*60);
               
               
$presec = '0.'.$min[1];
               
$sec = $presec*60;

               
$timeshift = $prehour[0].' hrs '.$min[0].' min '.round($sec,0).' sec ';

        } elseif(
$time>=86400) {
               
// Days + Hours + Minutes
               
$pday = ($edate - $sdate) / 86400;
               
$preday = explode('.',$pday);

               
$phour = $pday-$preday[0];
               
$prehour = explode('.',$phour*24);

               
$premin = ($phour*24)-$prehour[0];
               
$min = explode('.',$premin*60);
               
               
$presec = '0.'.$min[1];
               
$sec = $presec*60;
               
               
$timeshift = $preday[0].' days '.$prehour[0].' hrs '.$min[0].' min '.round($sec,0).' sec ';

        }
        return
$timeshift;
}

// EXAMPLE:

$start_date = 2010-03-15 13:00:00
$end_date
= 2010-03-17 09:36:15

echo date_diff($start_date, $end_date);

?>

Returns: 1days 20hours 36min 15sec
Can be taken up to centuries - if you do the calculations.

Hope this finally helps someone! :D

mark at dynom dot nl (02-Jul-2009 01:44)

If you simply want to compare two dates, using conditional operators works too:

<?php
$start
= new DateTime('08-06-1995 Europe/Copenhagen'); // DD-MM-YYYY
$end = new DateTime('22-11-1968 Europe/Amsterdam');

if (
$start < $end) {
    echo
"Correct order";
} else {
    echo
"Incorrect order, end date is before the starting date";
}
?>

tom at knapp2meter dot tk (16-Apr-2009 04:06)

A simple way to get the time lag (format: <hours>.<one-hundredth of one hour>).

Hier ein einfacher Weg zur Bestimmung der Zeitdifferenz (Format: <Stunden>.<hundertstel Stunde>).

<?php

function GetDeltaTime($dtTime1, $dtTime2)
{
 
$nUXDate1 = strtotime($dtTime1->format("Y-m-d H:i:s"));
 
$nUXDate2 = strtotime($dtTime2->format("Y-m-d H:i:s"));

 
$nUXDelta = $nUXDate1 - $nUXDate2;
 
$strDeltaTime = "" . $nUXDelta/60/60; // sec -> hour
           
 
$nPos = strpos($strDeltaTime, ".");
  if (
nPos !== false)
   
$strDeltaTime = substr($strDeltaTime, 0, $nPos + 3);

  return
$strDeltaTime;
}

?>