PHP code example of brtriver / date-range

1. Go to this page and download the library: Download brtriver/date-range library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

brtriver / date-range example snippets


use Brtriver\DateRange\DateRange;
$range = new DateRange('2015-12-01', '2015-12-31');

$range = new DateRange(['2015-12-01', '2015-12-31']);

$start = new DateTime('2012-12-01');
$end = new DateTime('2012-12-31');
$range = new DateRange([$start, $end]);

try {
  $range = new DateRange('tomorrow', 'today');
} catch (\InvalidArgumentException $e) {
  echo $e->getMessage();
  // end date is the day before than start date
}



# if you get start DateTime object.
$start = $range->getStart();

# if you get end DateTime object.
$end = $range->getEnd();

## check contains specific date
var_dump($range->contains('2015-12-10'));
// bool(true)

var_dump($range->contains('2017-01-10'));
// bool(false)


$range = new DateRange('2015-12-01', '2015-12-03');
$range->diff()->format('%R%a days');
// +2 days

$range = new DateRange('2015-12-01', '2015-12-03');
echo $range;
// '2015-12-01 ~ 2015-12-03'

$range = new DateRange('2015-12-01', '2015-12-03');
echo $range->toString('Y/m/d', '-');
// '2015/12/01 - 2015/12/03'

foreach ($range as $d) {
    echo $d->format('Y-m-d') . PHP_EOL;
}

foreach ($range->getDatePeriod() as $d) {
    echo $d->format('Y-m-d') . PHP_EOL;
}
// 2015-12-01
// 2015-12-02
// 2015-12-03
// 2015-12-04
// ...
// 2015-12-28
// 2015-12-29
// 2015-12-30
// 2015-12-31

## if you want to change interval, use setInterval()
$start = new DateTime('2012-12-01');
$end = new DateTime('2020-12-31');
$range = new DateRange([$start, $end]);
$range->setInterval(new DateInterval('P1Y')); // change from 'P1D' (Default)
foreach ($range->getDatePeriod() as $d) {
    echo $d->format('Y-m-d') . PHP_EOL;
}
// 2012-12-01
// 2013-12-01
// 2014-12-01
// 2015-12-01
// 2016-12-01
// 2017-12-01
// 2018-12-01
// 2019-12-01
// 2020-12-01

// exclude start date
$range = new DateRange('2015-12-01', '2015-12-03');
$range->excludeStartDate();
foreach ($range => $d) {
    echo $d->format('Y-m-d') . PHP_EOL;
}
// 2015-12-02
// 2015-12-03

// exclude end date
$range = new DateRange('2015-12-01', '2015-12-03');
$range->excludeEndDate();
foreach ($range => $d) {
    echo $d->format('Y-m-d') . PHP_EOL;
}
// 2015-12-01
// 2015-12-02