diff --git a/src/Carbon/Carbon.php b/src/Carbon/Carbon.php index 72fe98d705..ff552bee19 100644 --- a/src/Carbon/Carbon.php +++ b/src/Carbon/Carbon.php @@ -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 //////////////////////////// /////////////////////////////////////////////////////////////////// diff --git a/tests/DiffTest.php b/tests/DiffTest.php index c34c8924bd..9563011911 100644 --- a/tests/DiffTest.php +++ b/tests/DiffTest.php @@ -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();