Skip to content

Commit

Permalink
Merge pull request #65 from lucasmichot/feature/average
Browse files Browse the repository at this point in the history
Add average function
  • Loading branch information
briannesbitt committed Dec 5, 2013
2 parents b0450b5 + 54e3616 commit 51bc5af
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Carbon/Carbon.php
Original file line number Diff line number Diff line change
Expand Up @@ -1722,6 +1722,20 @@ public function diffForHumans(Carbon $other = null)
return $txt . ' before';
}

/**
* Get the average of two dates
*
* @param Carbon $dt
*
* @return Carbon
*/
public function average(Carbon $dt = null)
{
$dt = ($dt === null) ? static::now($this->tz) : $dt;

return $this->addSeconds(intval($this->diffInSeconds($dt, false) / 2));
}

///////////////////////////////////////////////////////////////////
//////////////////////////// MODIFIERS ////////////////////////////
///////////////////////////////////////////////////////////////////
Expand Down
24 changes: 24 additions & 0 deletions tests/DiffTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,30 @@ public function testDiffForHumansNowAndFutureYears()
$this->assertSame('2 years from now', $d->diffForHumans());
}

public function testAverageIsFluid()
{
$dt = Carbon::now()->average();
$this->assertTrue($dt instanceof Carbon);
}
public function testAverageFromSame()
{
$dt1 = Carbon::create(2000, 1, 31, 2, 3, 4);
$dt2 = Carbon::create(2000, 1, 31, 2, 3, 4)->average($dt1);
$this->assertCarbon($dt2, 2000, 1, 31, 2, 3, 4);
}
public function testAverageFromGreater()
{
$dt1 = Carbon::create(2000, 1, 1, 1, 1, 1);
$dt2 = Carbon::create(2009, 12, 31, 23, 59, 59)->average($dt1);
$this->assertCarbon($dt2, 2004, 12, 31, 12, 30, 30);
}
public function testAverageFromLower()
{
$dt1 = Carbon::create(2009, 12, 31, 23, 59, 59);
$dt2 = Carbon::create(2000, 1, 1, 1, 1, 1)->average($dt1);
$this->assertCarbon($dt2, 2004, 12, 31, 12, 30, 30);
}

public function testDiffForHumansOtherAndSecond()
{
$d = Carbon::now()->addSecond();
Expand Down

0 comments on commit 51bc5af

Please sign in to comment.