PHP Unconference Europe 2015

date_diff

(PHP 5 >= 5.3.0)

date_diffAlias de DateTime::diff()

Description

Cette fonction est un alias de : DateTime::diff()

add a note add a note

User Contributed Notes 11 notes

up
11
SunilKmCharde
5 months 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
23
Sergio Abreu
4 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
2
kshegunov at gmail dot com
3 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
jesushuertaarrabal at gmail dot com
28 days 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
0
waiyanmintun at gmail dot com
28 days ago
Why PHP skip counting 1914-1-2 in 5.5.11.0?

$d1 = date_create('1914-1-1');
$d2 = date_create('1914-1-3');
$interval = date_diff($d1, $d2);
$i = (int) $interval->format('%a');
echo $i;

$i value must be 2, but show 1.

Environment : XAMPP 3.2.1 on Win 8.1
up
-1
Flavio Tubino
4 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
-3
Chiheb Nabil
1 year 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
-5
tom at knapp2meter dot tk
5 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
-9
Toine (contact at toine dot pro)
3 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
-11
programacion at mundosica dot com
2 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
-5
vglebov at gmail dot com
3 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