Skip to content

Instantly share code, notes, and snippets.

@ignasbernotas
Created April 20, 2017 12:10
Show Gist options
  • Save ignasbernotas/ed8fd60c5cf63f101a85ee037ec80ea0 to your computer and use it in GitHub Desktop.
Save ignasbernotas/ed8fd60c5cf63f101a85ee037ec80ea0 to your computer and use it in GitHub Desktop.
DateRange
<?php
namespace App\Libraries\Date;
use Carbon\Carbon;
/**
* Class DateRange
*
* @package App\Libraries\Date
*/
class DateRange
{
/**
* @var Carbon
*/
protected $startDate;
/**
* @var Carbon
*/
protected $endDate;
/**
* DateRange constructor.
*
* @param Carbon $startDate
* @param Carbon $endDate
*/
public function __construct(Carbon $startDate, Carbon $endDate)
{
$this->startDate = $startDate;
$this->endDate = $endDate;
}
/**
* @return Carbon
*/
public function getStartDate()
{
return $this->startDate;
}
/**
* @return Carbon
*/
public function getEndDate()
{
return $this->endDate;
}
/**
* @return DateRange
*/
public function getMonthAgo()
{
return new self(
$this->getStartDate()->copy()->subMonth(),
$this->getEndDate()->copy()->subMonth()
);
}
/**
* @param int $months
*
* @return static
*/
public static function createMonthsAgo($months = 2)
{
$startDate = Carbon::create(null, null, 1, 0, 0, 0, 'UTC')->subMonths($months);
$endDate = Carbon::create(null, null, null, 0, 0, 0, 'UTC');
$dateRange = new static($startDate, $endDate);
return $dateRange;
}
/**
* @param int $days
*
* @return static
*/
public static function createDaysAgo($days = 2)
{
$startDate = Carbon::create(null, null, 1, 0, 0, 0, 'UTC')->subDays($days);
$endDate = Carbon::create(null, null, null, 0, 0, 0, 'UTC');
$dateRange = new static($startDate, $endDate);
return $dateRange;
}
/**
* @return \Illuminate\Support\Collection
*/
public function getDaysInBetween()
{
$interval = new \DateInterval('P1D');
$range = new \DatePeriod($this->startDate, $interval, $this->endDate);
return collect($range);
}
/**
* @return \Illuminate\Support\Collection
*/
public function getMonthsInBetween()
{
$interval = new \DateInterval('P1M');
$range = new \DatePeriod($this->startDate, $interval, $this->endDate);
return collect($range);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment