date_diff

(PHP 5 >= 5.3.0)

date_diffSinônimo de DateTime::diff()

Descrição

Esta função é um apelido para: DateTime::diff()

add a note add a note

User Contributed Notes 14 notes

up
40
Sergio Abreu
5 years ago
<?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 ;-) */
?>
up
18
SunilKmCharde
1 year ago
Powerful Function to get two date difference.

//////////////////////////////////////////////////////////////////////
//PARA: Date Should In YYYY-MM-DD Format
//RESULT FORMAT:
// '%y Year %m Month %d Day %h Hours %i Minute %s Seconds'        =>  1 Year 3 Month 14 Day 11 Hours 49 Minute 36 Seconds
// '%y Year %m Month %d Day'                                    =>  1 Year 3 Month 14 Days
// '%m Month %d Day'                                            =>  3 Month 14 Day
// '%d Day %h Hours'                                            =>  14 Day 11 Hours
// '%d Day'                                                        =>  14 Days
// '%h Hours %i Minute %s Seconds'                                =>  11 Hours 49 Minute 36 Seconds
// '%i Minute %s Seconds'                                        =>  49 Minute 36 Seconds
// '%h Hours                                                    =>  11 Hours
// '%a Days                                                        =>  468 Days
//////////////////////////////////////////////////////////////////////
function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
{
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);
   
    $interval = date_diff($datetime1, $datetime2);
   
    return $interval->format($differenceFormat);
   
}
up
0
tuxedobob
1 month ago
Even the top rated comment here, Sergio Abreu's, doesn't treat leap years entirely correctly. It should work between 1901 and 2099, but outside that it'll be a little off.

If you want to find out the number of days between two dates, use below. You can change to a different unit from that. It looks a little insane, but keep in mind the full set of rules for leap years:

If the year is divisible by 4, it's a leap year...
- unless the year is divisible by 100, then it isn't...
- - unless the year is divisible by 400, then it really is.

So in the functions below, we find the total numbers of days in full years since the mythical 1/1/0001, then add the number of days before the current one in the year passed. Do this for each date, then return the absolute value of the difference.

function days_diff($d1, $d2) {
    $x1 = days($d1);
    $x2 = days($d2);
   
    if ($x1 && $x2) {
        return abs($x1 - $x2);
    }
}

function days($x) {
    if (get_class($x) != 'DateTime') {
        return false;
    }
   
    $y = $x->format('Y') - 1;
    $days = $y * 365;
    $z = (int)($y / 4);
    $days += $z;
    $z = (int)($y / 100);
    $days -= $z;
    $z = (int)($y / 400);
    $days += $z;
    $days += $x->format('z');

    return $days;
}
up
0
Azuro
4 months ago
I had to find the difference between two days (here is my solution without Date_diff()) :

$current_date = date("U") /* to have it in microseconds */
$selected_date_stamp = mktime(0,0,0,$your_month,$your_day,$your_year);
$selected_date = date("U",$selected_date_stamp);
$difference = round (($current_date - $selected_date)/(3600*24));
echo "The difference is :" . $difference . "<br/>";
up
-1
Flavio Tubino
5 years ago
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);

}
?>
up
-1
jesushuertaarrabal at gmail dot com
10 months ago
A way to verify a correct date getting your age

if (isset($_POST['birthday'])){
     if (preg_match("/^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$/",$_POST['birthday'])){
          $items = explode("-", $_POST['birthday']);
           if (checkdate($items[1], $items[2], $items[0])){ //checkdate(m-d-y)
               //If you were born in a lip-year or lip - 1, then we have to add 5 days, else, we add 4 days
                if ((0 == $items[0] % 4) && (0 != $items[0] % 100) || (0 == $items[0] % 400))
                 $bis = 4;
                else
                 $bis = 5;
            if (date_diff(date_create($_POST['birthday']) , date_create(date('Y-m-d')))->format("%R%a days") > (6569 + $bis)) //365*18
                 $print .= 'Birthday date: ' . $_POST['birthday'] . '<br>';
            else
                 $error[] = -1;
           }else
                $error[] = -2;
      }else
           $error[] = -3;
     }else
    $error[] = -4;
}
up
-2
kshegunov at gmail dot com
4 years ago
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);
        }
?>
up
-1
qrworld.net
8 months ago
Here you have in this post http://softontherocks.blogspot.com/2014/12/calcular-la-edad-con-php.html the code to get the age of a person specifying the date of birth:

function getAge($birthdate){
    $adjust = (date("md") >= date("md", strtotime($birthdate))) ? 0 : -1; // Si aún no hemos llegado al día y mes en este año restamos 1
    $years = date("Y") - date("Y", strtotime($birthdate)); // Calculamos el número de años
    return $years + $adjust; // Sumamos la diferencia de años más el ajuste
}
up
-7
Chiheb Nabil
2 years ago
here a little solution of problem of missing date_diff function with php versions below 5.3.0

<?php
function IntervalDays($CheckIn,$CheckOut){
$CheckInX = explode("-", $CheckIn);
$CheckOutX explode("-", $CheckOut);
$date1 mktime(0, 0, 0, $CheckInX[1],$CheckInX[2],$CheckInX[0]);
$date2 mktime(0, 0, 0, $CheckOutX[1],$CheckOutX[2],$CheckOutX[0]);
$interval =($date2 - $date1)/(3600*24);

// returns numberofdays
return  $interval ;

}
?>
up
-7
tom at knapp2meter dot tk
6 years ago
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;
}

?>
up
-12
Toine (contact at toine dot pro)
4 years ago
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
?>
up
-14
programacion at mundosica dot com
3 years ago
Other data_diff aviable for php5.3>=

<?php
// Author: el pinche <fitorec>

function otherDiffDate($end='2020-06-09 10:30:00', $out_in_array=false){
       
$intervalo = date_diff(date_create(), date_create($end));
       
$out = $intervalo->format("Years:%Y,Months:%M,Days:%d,Hours:%H,Minutes:%i,Seconds:%s");
        if(!
$out_in_array)
            return
$out;
       
$a_out = array();
       
array_walk(explode(',',$out),
        function(
$val,$key) use(&$a_out){
           
$v=explode(':',$val);
           
$a_out[$v[0]] = $v[1];
        });
        return
$a_out;
}
?>

#example 1
<?php
echo otherDiffDate();
?>
out1
       Years:08,Months:01,Days:22,Hours:17,Minutes:5,Seconds:26

example2
<?php
print_r
(otherDiffDate('2020-01-01 20:30:00',true));
?>
out2
Array
(
    [Years] => 07
    [Months] => 08
    [Days] => 15
    [Hours] => 03
    [Minutes] => 3
    [Seconds] => 48
)
up
-2
maniarpratik at gmail dot com
6 months ago
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;
}
?>
up
-8
vglebov at gmail dot com
4 years ago
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);
?>
To Top