You are here

public function DatexObject::difference in Datex 7.2

Same name and namespace in other branches
  1. 7 datex_api/datex_api_classes.inc \DatexObject::difference()

Returns amount of time difference to another date object

@TODO properly implement.

File

datex_api/datex_api.class.inc, line 411
Provides an API to work with dates.

Class

DatexObject
Base class for localized DateTime.

Code

public function difference(DatexObject $date2_in, $measure = 'seconds', $absolute = TRUE) {

  // Create cloned objects or original dates will be impacted by the
  // date_modify() operations done in this code.
  $date1 = clone $this;
  $date2 = clone $date2_in;
  $diff = $date2
    ->format('U') - $date1
    ->format('U');
  if ($diff == 0) {
    return 0;
  }
  elseif ($diff < 0 && $absolute) {

    // Make sure $date1 is the smaller date.
    $temp = $date2;
    $date2 = $date1;
    $date1 = $temp;
    $diff = $date2
      ->format('U') - $date1
      ->format('U');
  }
  $year_diff = intval($date2
    ->format('Y') - $date1
    ->format('Y'));
  switch ($measure) {
    case 'seconds':
      return $diff;
    case 'minutes':
      return $diff / 60;
    case 'hours':
      return $diff / 3600;
    case 'years':
      return $year_diff;
    case 'months':
      $item1 = $date1
        ->format('n');
      $item2 = $date2
        ->format('n');
      if ($year_diff == 0) {
        return intval($item2 - $item1);
      }
      else {
        $item_diff = 12 - $item1;
        $item_diff += intval(($year_diff - 1) * 12);
        return $item_diff + $item2;
      }
      break;
    case 'days':
      break;
      $item1 = $date1
        ->format('z');
      $item2 = $date2
        ->format('z');
      if ($year_diff == 0) {
        return intval($item2 - $item1);
      }
      else {
        $item_diff = date_days_in_year($date1) - $item1;
        for ($i = 1; $i < $year_diff; $i++) {
          date_modify($date1, '+1 year');
          $item_diff += date_days_in_year($date1);
        }
        return $item_diff + $item2;
      }
      break;
    case 'weeks':
    default:
      break;
  }
  return NULL;
}