Carbon中文使用手冊(下)

piny發表於2021-09-09

·         Serialization

Carbon例項能被序列化的。

$dt = Carbon::create(2012, 12, 25, 20, 30, 00, 'Europe/Moscow');

echo serialize($dt);                                              // O:13:"CarbonCarbon":3:{s:4:"date";s:26:"2012-12-25 20:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:13:"Europe/Moscow";}
// 
等同於:
echo $dt->serialize();                                            // O:13:"CarbonCarbon":3:{s:4:"date";s:26:"2012-12-25 20:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:13:"Europe/Moscow";}

$dt = 'O:13:"CarbonCarbon":3:{s:4:"date";s:26:"2012-12-25 20:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:13:"Europe/Moscow";}';

echo unserialize($dt)->format('Y-m-dTH:i:s.uP T');               // 2012-12-25T20:30:00.000000+04:00 MSK
// 等同於:
echo Carbon::fromSerialized($dt)->format('Y-m-dTH:i:s.uP T');    // 2012-12-25T20:30:00.000000+04:00 MSK

·         JSON

Carbon例項可以從JSON編碼和解碼(這些特性只能從PHP 5.4+中獲得,參見下面關於PHP 5.3的註釋)

$dt = Carbon::create(2012, 12, 25, 20, 30, 00, 'Europe/Moscow');
echo json_encode($dt);
// {"date":"2012-12-25 20:30:00.000000","timezone_type":3,"timezone":"Europe/Moscow"}

$json = '{"date":"2012-12-25 20:30:00.000000","timezone_type":3,"timezone":"Europe/Moscow"}';
$dt = Carbon::__set_state(json_decode($json, true));
echo $dt->format('Y-m-dTH:i:s.uP T');
// 2012-12-25T20:30:00.000000+04:00 MSK

您可以使用serializeUsing()自定義序列化。

$dt = Carbon::create(2012, 12, 25, 20, 30, 00, 'Europe/Moscow');
Carbon::serializeUsing(function ($date) {
    return $date->getTimestamp();
});
echo json_encode($dt);


// Call serializeUsing with null to reset the serializer:
Carbon::serializeUsing(null);

jsonSerialize()方法返回中間透過“json_encode”將其轉換為字串,它還允許您使用PHP 5.3相容性。

$dt = Carbon::create(2012, 12, 25, 20, 30, 00, 'Europe/Moscow');
echo json_encode($dt->jsonSerialize());
// {"date":"2012-12-25 20:30:00.000000","timezone_type":3,"timezone":"Europe/Moscow"}
// This is equivalent to the first json_encode example but works with PHP 5.3.

// And it can be used separately:
var_dump($dt->jsonSerialize());
// array(3) {
["date"]=>
  string(26) "2012-12-25 20:30:00.000000"
["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13) "Europe/Moscow"
}

·         Macro

如果您習慣於使用Laravel和物件(如響應或集合),您可能熟悉這個宏概念。Carbon macro()的工作方式與Laravel宏特性相同,它將方法名作為第一個引數,閉包作為第二個引數。這使得閉包操作可以作為一個具有給定名稱的方法在所有Carbon例項(也可以作為Carbon static方法)上使用。

PHP 5.4中,$this可用於閉包中引用當前例項。對於PHP 5.3的相容性,我們還向閉包新增了一個“$self”屬性。例子:

Carbon::macro('diffFromYear', function ($year, $self = null) {
    // 
這個塊是為了在獨立的Carbon上與PHP版本     if (!isset($self) && isset($this)) {
        $self = $this;
    }
    //相容性塊的結束。

    return $self->diffForHumans(Carbon::create($year, 1, 1, 0, 0, 0), false, false, 3);
});
echo Carbon::parse('2020-01-12 12:00:00')->diffFromYear(2019);                 // 1 year 1 week 4 days after

相容性塊允許您確保宏的完全相容性。一個關於IlluminateSupportCarbon (Laravel包裝類)的宏將不會被定義,正如上面在PHP 5.3 $this中提到的,這個不會被定義。要使宏在任何地方都能工作,只需貼上這個if語句測試如果它是定義的,而不是$self然後複製它,然後在函式體中使用$self

不管您是否省略了一些可選引數,只要$self有這個名稱,並且是最後一個引數:

Carbon::macro('diffFromYear', function ($year, $absolute = false, $short = false, $parts = 1, $self = null) {
    // compatibility chunk
    if (!isset($self) && isset($this)) {
        $self = $this;
    }

    return $self->diffForHumans(Carbon::create($year, 1, 1, 0, 0, 0), $absolute, $short, $parts);
});

echo Carbon::parse('2020-01-12 12:00:00')->diffFromYear(2019);                 // 1 year after
echo Carbon::parse('2020-01-12 12:00:00')->diffFromYear(2019, true);           // 1 year
echo Carbon::parse('2020-01-12 12:00:00')->diffFromYear(2019, true, true);     // 1yr
echo Carbon::parse('2020-01-12 12:00:00')->diffFromYear(2019, true, true, 5);  // 1yr 1w 4d 12h

還可以將宏分組到類中,並與mixin()一起應用

Class BeerDayCarbonMixin
{
    public function nextBeerDay()
    {
        return function ($self = null) {
            // compatibility chunk
            if (!isset($self) && isset($this)) {
                $self = $this;
            }

            return $self->modify('next wednesday');
        };
    }

    public function previousBeerDay()
    {
        return function ($self = null) {
            // compatibility chunk
            if (!isset($self) && isset($this)) {
                $self = $this;
            }

            return $self->modify('previous wednesday');
        };
    }
}

Carbon::mixin(new BeerDayCarbonMixin());

$date = Carbon::parse('First saturday of December 2018');

echo $date->previousBeerDay();                                                 // 2018-11-28 00:00:00
echo $date->nextBeerDay();                                                     // 2018-12-05 00:00:00

您可以用hasMacro()檢查是否可用宏(包括mixin)

var_dump(Carbon::hasMacro('previousBeerDay'));                                 // bool(true)
var_dump(Carbon::hasMacro('diffFromYear'));                                    // bool(true)
var_dump(Carbon::hasMacro('dontKnowWhat'));                                    // bool(false)

你猜怎麼著?CarbonIntervalCarbonPeriod類上也可以使用所有的宏方法。

CarbonInterval::macro('twice', function ($self = null) {
    return $self->times(2);
});
echo CarbonInterval::day()->twice()->forHumans();                        // 2 days
echo CarbonInterval::hours(2)->minutes(15)->twice()->forHumans(true);    // 4h 30m

CarbonPeriod::macro('countWeekdays', function ($self = null) {
    return $self->filter('isWeekday')->count();
});
echo CarbonPeriod::create('2017-11-01', '2017-11-30')->countWeekdays();  // 22
echo CarbonPeriod::create('2017-12-01', '2017-12-31')->countWeekdays();  // 21

以下是社群提出的一些有用的宏:

Carbon::macro('isHoliday', function ($self = null) {
    // compatibility chunk
    if (!isset($self) && isset($this)) {
        $self = $this;
    }

    return in_array($self->format('d/m'), [
        '25/12', // Christmas
        '01/01', // New Year
        // ...
    ]);
});
var_dump(Carbon::createMidnightDate(2012, 12, 25)->isHoliday());  // bool(true)
var_dump(Carbon::createMidnightDate(2017, 6, 25)->isHoliday());   // bool(false)
var_dump(Carbon::createMidnightDate(2021, 1, 1)->isHoliday());    // bool(true)

Credit:kylekatarnls(# 116)

檢查cmixin/業務日以獲得更完整的業務日處理程式。

Class CurrentDaysCarbonMixin
{
    
    public static function getCurrentWeekDays()
    {
        return function ($self = null) {
            // compatibility chunk
            if (!isset($self) && isset($this)) {
                $self = $this;
            }

            $startOfWeek = ($self ?: static::now())->startOfWeek()->subDay();
            $weekDays = array();

            for ($i = 0; $i                  $weekDays[] = $startOfWeek->addDay()->startOfDay()->copy();
            }

            return $weekDays;
        };
    }

    
    public static function getCurrentMonthDays()
    {
        return function ($self = null) {
            // compatibility chunk
            if (!isset($self) && isset($this)) {
                $self = $this;
            }

            $startOfMonth = ($self ?: static::now())->startOfMonth()->subDay();
            $endOfMonth = ($self ?: static::now())->endOfMonth()->format('d');
            $monthDays = array();

            for ($i = 0; $i              {
                $monthDays[] = $startOfMonth->addDay()->startOfDay()->copy();
            }

            return $monthDays;
        };
    }
}

Carbon::mixin(new CurrentDaysCarbonMixin());

function dumpDateList($dates) {
    echo substr(implode(', ', $dates), 0, 100).'...';
}

dumpDateList(Carbon::getCurrentWeekDays());                       // 2018-07-02 00:00:00, 2018-07-03 00:00:00, 2018-07-04 00:00:00, 2018-07-05 00:00:00, 2018-07-06 00:00...
dumpDateList(Carbon::getCurrentMonthDays());                      // 2018-07-01 00:00:00, 2018-07-02 00:00:00, 2018-07-03 00:00:00, 2018-07-04 00:00:00, 2018-07-05 00:00...
dumpDateList(Carbon::now()->subMonth()->getCurrentWeekDays());    // 2018-06-04 00:00:00, 2018-06-05 00:00:00, 2018-06-06 00:00:00, 2018-06-07 00:00:00, 2018-06-08 00:00...
dumpDateList(Carbon::now()->subMonth()->getCurrentMonthDays());   // 2018-06-01 00:00:00, 2018-06-02 00:00:00, 2018-06-03 00:00:00, 2018-06-04 00:00:00, 2018-06-05 00:00...

Credit:  ().

Carbon::macro('toAtomStringWithNoTimezone', function ($self = null) {
    // compatibility chunk
    if (!isset($self) && isset($this)) {
        $self = $this;
    }

    return $self->format('Y-m-dTH:i:s');
});
echo Carbon::parse('2021-06-16 20:08:34')->toAtomStringWithNoTimezone(); // 2021-06-16T20:08:34

Credit:  ().

Carbon::macro('easterDate', function ($year) {    
    return Carbon::createMidnightDate($year, 3, 21)->addDays(easter_days($year));
});
    echo Carbon::easterDate(2015)->format('d/m'); // 05/04
    echo Carbon::easterDate(2016)->format('d/m'); // 27/03
    echo Carbon::easterDate(2017)->format('d/m'); // 16/04
    echo Carbon::easterDate(2018)->format('d/m'); // 01/04
    echo Carbon::easterDate(2019)->format('d/m'); // 21/04

Credit: ,  ().

檢視cmixin/工作日以獲得更完整的假日處理程式。

Carbon::macro('range', function ($startDate, $endDate) {
    return new DatePeriod($startDate, new DateInterval('P1D'), $endDate);
});
foreach (Carbon::range(Carbon::createMidnightDate(2019, 3, 28), Carbon::createMidnightDate(2019, 4, 3)) as $date) {
    echo "$daten";
}

Credit:  ().

class UserTimezoneCarbonMixin
{
    public $userTimeZone;

    
    public function setUserTimezone()
    {
        $mixin = $this;

        return function ($timezone) use ($mixin) {
            $mixin->userTimeZone = $timezone;
        };
    }

    
    public function tzFormat()
    {
        $mixin = $this;

        return function ($format, $self = null) use ($mixin) {
            // compatibility chunk
            if (!isset($self) && isset($this)) {
                $self = $this;
            }

            if (!is_null($mixin->userTimeZone)) {
                $self->timezone($mixin->userTimeZone);
            }

            return $self->format($format);
        };
    }
}

Carbon::mixin(new UserTimezoneCarbonMixin());

Carbon::setUserTimezone('Europe/Berlin');
echo Carbon::createFromTime(12, 0, 0, 'UTC')->tzFormat('H:i'); // 14:00
echo Carbon::createFromTime(15, 0, 0, 'UTC')->tzFormat('H:i'); // 17:00
Carbon::setUserTimezone('America/Toronto');
echo Carbon::createFromTime(12, 0, 0, 'UTC')->tzFormat('H:i'); // 08:00
echo Carbon::createFromTime(15, 0, 0, 'UTC')->tzFormat('H:i'); // 11:00

Credit:  ().

·         CarbonInterval

CarbonInterval類繼承了PHP DateInterval類。

class CarbonInterval extends DateInterval
{    
    // code here
}

你可以透過以下方式建立例項

echo CarbonInterval::year();                           // 1 year
echo CarbonInterval::months(3);                        // 3 months
echo CarbonInterval::days(3)->seconds(32);             // 3 days 32 seconds
echo CarbonInterval::weeks(3);                         // 3 weeks
echo CarbonInterval::days(23);                         // 3 weeks 2 days
echo CarbonInterval::create(2, 0, 5, 1, 1, 2, 7);      // 2 years 5 weeks 1 day 1 hour 2 minutes 7 seconds

如果您發現自己從另一個庫繼承了DateInterval例項,不要害怕!您可以透過一個友好的instance()函式建立一個CarbonInterval例項。

$di = new DateInterval('P1Y2M'); //  $ci = CarbonInterval::instance($di);
echo get_class($ci);                                   // 'CarbonCarbonInterval'
echo $ci;                                              // 1 year 2 months

其他的幫助程式,但是要注意實現提供了幫助程式來處理幾周,但是隻節省了幾天。數週是根據當前例項的總天數計算的。

echo CarbonInterval::year()->years;                    // 1
echo CarbonInterval::year()->dayz;                     // 0
echo CarbonInterval::days(24)->dayz;                   // 24
echo CarbonInterval::days(24)->daysExcludeWeeks;       // 3
echo CarbonInterval::weeks(3)->days(14)->weeks;        // 2   echo CarbonInterval::weeks(3)->weeks;                  // 3
echo CarbonInterval::minutes(3)->weeksAndDays(2, 5);   // 2 weeks 5 days 3 minutes

CarbonInterval擴充套件DateInterval,您可以使用ISO-8601的持續時間格式建立這兩種格式:

$ci = CarbonInterval::create('P1Y2M3D');
$ci = new CarbonInterval('PT0S');

藉助fromString()方法,可以從友好的字串建立Carbon intervals

CarbonInterval::fromString('2 minutes 15 seconds');

 CarbonInterval::fromString('2m 15s'); // or abbreviated

注意這個月縮寫為“mo”以區別於分鐘和整個語法不區分大小寫。

它還有一個方便的for human(),它被對映為__toString()實現,用於為人類列印間隔。

CarbonInterval::setLocale('fr');
echo CarbonInterval::create(2, 1)->forHumans();        // 2 ans 1 mois
echo CarbonInterval::hour()->seconds(3);               // 1 heure 3 secondes
CarbonInterval::setLocale('en');

如您所見,您可以使用CarbonInterval::setLocale('fr')更改字串的語言環境。

至於Carbon,您可以使用make方法從其他區間或字串返回一個新的CarbonInterval例項:

$dateInterval = new DateInterval('P2D');
$carbonInterval = CarbonInterval::month();
echo CarbonInterval::make($dateInterval)->forHumans();       // 2 days
echo CarbonInterval::make($carbonInterval)->forHumans();     // 1 month
echo CarbonInterval::make('PT3H')->forHumans();              // 3 hours
echo CarbonInterval::make('1h 15m')->forHumans();            // 1 hour 15 minutes
// Pass true to get short format
echo CarbonInterval::make('1h 15m')->forHumans(true);        // 1h 15m

本機DateInterval分別新增和相乘,因此:

$interval = CarbonInterval::make('7h 55m');
$interval->add(CarbonInterval::make('17h 35m'));
$interval->times(3);
echo $interval->forHumans(); // 72 hours 270 minutes

從單位到單位的輸入中得到純計算。將分鐘級聯成小時、小時級聯成天等。使用級聯方法:

echo $interval->forHumans();             // 72 hours 270 minutes
echo $interval->cascade()->forHumans();  // 3 days 4 hours 30 minutes

預設的因素有:

1分鐘= 60

1小時=60分鐘

1=24小時

1= 7

1個月= 4

1= 12個月

CarbonIntervals 沒有上下文,所以它們不能更精確(沒有DST、沒有閏年、沒有實際的月長或年長)。但是你可以完全定製這些因素。例如處理工作時間日誌:

$cascades = CarbonInterval::getCascadeFactors(); // save initial factors

CarbonInterval::setCascadeFactors(array(
    'minute' => array(60, 'seconds'),
    'hour' => array(60, 'minutes'),
    'day' => array(8, 'hours'),
    'week' => array(5, 'days'),
    // in this example the cascade won't go farther than week unit
));

echo CarbonInterval::fromString('20h')->cascade()->forHumans();              // 2 days 4 hours
echo CarbonInterval::fromString('10d')->cascade()->forHumans();              // 2 weeks
echo CarbonInterval::fromString('3w 18d 53h 159m')->cascade()->forHumans();  // 7 weeks 4 days 7 hours 39 minutes

// You can see currently set factors with getFactor:
echo CarbonInterval::getFactor('minutes', 'hour');                 // 60
echo CarbonInterval::getFactor('days', 'week');                              // 5

// And common factors can be get with short-cut methods:
echo CarbonInterval::getDaysPerWeek();                                       // 5
echo CarbonInterval::getHoursPerDay();                                       // 8
echo CarbonInterval::getMinutesPerHours();                                   // 60
echo CarbonInterval::getSecondsPerMinutes();                                 // 60

CarbonInterval::setCascadeFactors($cascades); // restore original factors

是否可能將間隔轉換為給定的單元(使用提供的級聯因子)

echo CarbonInterval::days(3)->hours(5)->total('hours');    // 77
echo CarbonInterval::days(3)->hours(5)->totalHours;        // 77
echo CarbonInterval::months(6)->totalWeeks;                // 24
echo CarbonInterval::year()->totalDays;                    // 336

您還可以使用spec()獲得invervalISO 8601規範

echo CarbonInterval::days(3)->hours(5)->spec(); // P3DT5H

也可以從DateInterval物件獲取它,因為它是靜態助手:

echo CarbonInterval::getDateIntervalSpec(new DateInterval('P3DT6M10S')); // P3DT6M10S

使用compare()comparedateinterval()方法可以對日期間隔列表進行排序:

$halfDay = CarbonInterval::hours(12);
$oneDay = CarbonInterval::day();
$twoDay = CarbonInterval::days(2);

echo CarbonInterval::compareDateIntervals($oneDay, $oneDay);   // 0
echo $oneDay->compare($oneDay);                                // 0
echo CarbonInterval::compareDateIntervals($oneDay, $halfDay);  // 1
echo $oneDay->compare($halfDay);                               // 1
echo CarbonInterval::compareDateIntervals($oneDay, $twoDay);   // -1
echo $oneDay->compare($twoDay);                                // -1

$list = array($twoDay, $halfDay, $oneDay);
usort($list, array('CarbonCarbonInterval', 'compareDateIntervals'));

echo implode(', ', $list);                                     // 12 hours, 1 day, 2 days

最後,透過使用互補引數呼叫toPeriod(),可以將一個CarbonInterval例項轉換為一個CarbonPeriod例項。 

我聽到你問什麼是CarbonPeriod 例項。哦!完美過渡到下一章。

·         CarbonPeriod

CarbonPeriod是一個友好的DatePeriod版本,具有許多快捷方式。

// Create a new instance:
$period = new CarbonPeriod('2018-04-21', '3 days', '2018-04-27');
// Use static constructor:
$period = CarbonPeriod::create('2018-04-21', '3 days', '2018-04-27');
// Use the fluent setters:
$period = CarbonPeriod::since('2018-04-21')->days(3)->until('2018-04-27');
// Start from a CarbonInterval:
$period = CarbonInterval::days(3)->toPeriod('2018-04-21', '2018-04-27');

CarbonPeriod可以透過多種方式構建:

開始日期、結束日期和可選間隔(預設為1)

起始日期,遞迴次數和可選區間,

ISO 8601間隔規範。

日期可以是DateTime/Carbon例項,絕對字串如“2007-10-15 15:00”或相對字串,例如“next monday”Interval可以作為DateInterval/CarbonInterval例項、ISO 8601Interval規範(“P4D”)或人類可讀字串(“4 days”)給出。

預設建構函式和create()方法在引數型別和順序方面都很容易理解,所以如果您想要更精確,建議使用fluent語法。另一方面,您可以將動態值陣列傳遞給createFromArray(),它將使用給定的陣列作為引數列表構造一個新例項。

CarbonPeriod實現迭代器介面。它意味著它可以直接傳遞給foreach迴圈:

$period = CarbonPeriod::create('2018-04-21', '3 days', '2018-04-27');
foreach ($period as $key => $date) {
    if ($key) {
        echo ', ';
    }
    echo $date->format('m-d');
}
// 04-21, 04-24, 04-27

// Here is what happens under the hood:
$period->rewind(); // restart the iteration
while ($period->valid()) { // check if current item is valid
    if ($period->key()) { // echo comma if current key is greater than 0
        echo ', ';
    }
    echo $period->current()->format('m-d'); // echo current date
    $period->next(); // move to the next item
}
// 04-21, 04-24, 04-27

引數可以在迭代過程中進行修改:

$period = CarbonPeriod::create('2018-04-29', 7);
$dates = array();
foreach ($period as $key => $date) {
    if ($key === 3) {
        $period->invert()->start($date); // invert() is an alias for invertDateInterval()
    }
    $dates[] = $date->format('m-d');
}

echo implode(', ', $dates); // 04-29, 04-30, 05-01, 05-02, 05-01, 04-30, 04-29

DatePeriod一樣,CarbonPeriod也支援ISO 8601時間間隔規範。

請注意,本機日期週期將遞迴處理為多次重複間隔。因此,在排除開始日期時,它將減少一個結果。CarbonPeriod的自定義過濾器的引入使得知道結果的數量變得更加困難。由於這個原因,我們稍微改變了實現,遞迴被視為返回日期的總體限制。

// Possible options are: CarbonPeriod::EXCLUDE_START_DATE | CarbonPeriod::EXCLUDE_END_DATE
// Default value is 0 which will have the same effect as when no options are given.
$period = CarbonPeriod::createFromIso('R4/2012-07-01T00:00:00Z/P7D', CarbonPeriod::EXCLUDE_START_DATE);
$dates = array();
foreach ($period as $date) {
    $dates[] = $date->format('m-d');
}

echo implode(', ', $dates); // 07-08, 07-15, 07-22, 07-29

您可以從不同的getter中檢索資料:

$period = CarbonPeriod::create('2010-05-06', '2010-05-25', CarbonPeriod::EXCLUDE_START_DATE);

$exclude = $period->getOptions() & CarbonPeriod::EXCLUDE_START_DATE;

echo $period->getStartDate();            // 2010-05-06 00:00:00
echo $period->getEndDate();              // 2010-05-25 00:00:00
echo $period->getDateInterval();         // 1 day
echo $exclude ? 'exclude' : 'include';   // exclude

var_dump($period->isStartExcluded());    // bool(true)
var_dump($period->isEndExcluded());      // bool(false)

echo $period->toString();                // Every 1 day from 2010-05-06 to 2010-05-25
echo $period;       // Every 1 day from 2010-05-06 to 2010-05-25

附加的getter允許您以陣列的形式訪問結果:

$period = CarbonPeriod::create('2010-05-11', '2010-05-13');

echo $period->count();                   // 3, equivalent to count($period)
echo implode(', ', $period->toArray());  // 2010-05-11 00:00:00, 2010-05-12 00:00:00, 2010-05-13 00:00:00
echo $period->first();                   // 2010-05-11 00:00:00
echo $period->last();                    // 2010-05-13 00:00:00

注意,如果您打算使用上述函式,將toArray()呼叫的結果儲存為變數並使用它是一個好主意,因為每個呼叫在內部執行一個完整的迭代。

想要更改引數,可以使用setter方法:

$period = CarbonPeriod::create('2010-05-01', '2010-05-14', CarbonPeriod::EXCLUDE_END_DATE);

$period->setStartDate('2010-05-11');
echo implode(', ', $period->toArray());  // 2010-05-11 00:00:00, 2010-05-12 00:00:00, 2010-05-13 00:00:00

// Second argument can be optionally used to exclude the date from the results.
$period->setStartDate('2010-05-11', false);
$period->setEndDate('2010-05-14', true);
echo implode(', ', $period->toArray());  // 2010-05-12 00:00:00, 2010-05-13 00:00:00, 2010-05-14 00:00:00

$period->setRecurrences(2);
echo implode(', ', $period->toArray());  // 2010-05-12 00:00:00, 2010-05-13 00:00:00

$period->setDateInterval('PT12H');
echo implode(', ', $period->toArray());  // 2010-05-11 12:00:00, 2010-05-12 00:00:00

您可以使用setOptions()更改選項以替換所有選項,但也可以分別更改:

$period = CarbonPeriod::create('2010-05-06', '2010-05-25');

var_dump($period->isStartExcluded());    // bool(false)
var_dump($period->isEndExcluded());      // bool(false)

$period->toggleOptions(CarbonPeriod::EXCLUDE_START_DATE, true); // true, false or nothing to invert the option
var_dump($period->isStartExcluded());    // bool(true)
var_dump($period->isEndExcluded());      // bool(false) (unchanged)

$period->excludeEndDate();               // specify false to include, true or omit to exclude
var_dump($period->isStartExcluded());    // bool(true) (unchanged)
var_dump($period->isEndExcluded());      // bool(true)

$period->excludeStartDate(false);        // specify false to include, true or omit to exclude
var_dump($period->isStartExcluded());    // bool(false)
var_dump($period->isEndExcluded());      // bool(true)

如前所述,根據ISO 8601規範,遞迴是重複間隔的數倍。因此,本機DatePeriod將根據開始日期的排除而改變返回日期的數量。與此同時,CarbonPeriod在輸入和允許自定義過濾器方面更加寬容,將遞迴作為返回日期的總體限制:

$period = CarbonPeriod::createFromIso('R4/2012-07-01T00:00:00Z/P7D');
$days = array();
foreach ($period as $date) {
    $days[] = $date->format('d');
}

echo $period->getRecurrences();          // 4
echo implode(', ', $days);               // 01, 08, 15, 22

$days = array();
$period->setRecurrences(3)->excludeStartDate();
foreach ($period as $date) {
    $days[] = $date->format('d');
}

echo $period->getRecurrences();          // 3
echo implode(', ', $days);               // 08, 15, 22

$days = array();
$period = CarbonPeriod::recurrences(3)->sinceNow();
foreach ($period as $date) {
    $days[] = $date->format('Y-m-d');
}

echo implode(', ', $days);               // 2018-07-05, 2018-07-06, 2018-07-07

DatePeriod返回的日期可以很容易地過濾。例如,過濾器可以用於跳過某些日期或只在工作日或週末迭代。篩選函式應該返回true以接受日期,返回false以跳過日期,但繼續搜尋或CarbonPeriod::END_ITERATION以結束迭代。

$period = CarbonPeriod::between('2000-01-01', '2000-01-15');
$weekendFilter = function ($date) {
    return $date->isWeekend();
};
$period->filter($weekendFilter);

$days = array();
foreach ($period as $date) {
    $days[] = $date->format('m-d');
}
echo implode(', ', $days);                         // 01-01, 01-02, 01-08, 01-09, 01-15

您還可以跳過迴圈中的一個或多個值。

$period = CarbonPeriod::between('2000-01-01', '2000-01-10');
$days = array();
foreach ($period as $date) {
    $day = $date->format('m-d');
    $days[] = $day;
    if ($day === '01-04') {
        $period->skip(3);
    }
}
echo implode(', ', $days);                         // 01-01, 01-02, 01-03, 01-04, 01-08, 01-09, 01-10

getFilters()允許您在一個時間段內檢索所有儲存的過濾器。但是要注意遞迴限制和結束日期將出現在返回的陣列中,因為它們作為過濾器儲存在內部。

$period = CarbonPeriod::end('2000-01-01')->recurrences(3);
var_export($period->getFilters());

過濾器儲存在堆疊中,可以使用一組特殊的方法進行管理:

$period = CarbonPeriod::between('2000-01-01', '2000-01-15');
$weekendFilter = function ($date) {
    return $date->isWeekend();
};

var_dump($period->hasFilter($weekendFilter));      // bool(false)
$period->addFilter($weekendFilter);
var_dump($period->hasFilter($weekendFilter));      // bool(true)
$period->removeFilter($weekendFilter);
var_dump($period->hasFilter($weekendFilter));      // bool(false)

// To avoid storing filters as variables you can name your filters:
$period->prependFilter(function ($date) {
    return $date->isWeekend();
}, 'weekend');

var_dump($period->hasFilter('weekend'));           // bool(true)
$period->removeFilter('weekend');
var_dump($period->hasFilter('weekend'));           // bool(false)

新增過濾器的順序會對效能和結果產生影響,因此您可以使用addFilter()在堆疊末尾新增過濾器;您可以使用prependFilter()在開始時新增一個。甚至可以使用setfilter()替換所有的過濾器。請注意,您必須保持堆疊的正確格式,並記住關於遞迴限制和結束日期的內部過濾器。或者,您可以使用resetFilters()方法,然後逐個新增新的過濾器。

例如,當您新增一個限制嘗試日期數量的自定義過濾器時,如果您在工作日過濾器之前或之後新增它,那麼結果將是不同的。

// Note that you can pass a name of any Carbon method starting with "is", including macros
$period = CarbonPeriod::between('2018-05-03', '2018-05-25')->filter('isWeekday');

$attempts = 0;
$attemptsFilter = function () use (&$attempts) {
    return ++$attempts };

$period->prependFilter($attemptsFilter, 'attempts');
$days = array();
foreach ($period as $date) {
    $days[] = $date->format('m-d');
}
echo implode(', ', $days);                         // 05-03, 05-04, 05-07

$attempts = 0;

$period->removeFilter($attemptsFilter)->addFilter($attemptsFilter, 'attempts');
$days = array();
foreach ($period as $date) {
    $days[] = $date->format('m-d');
}
echo implode(', ', $days);                         // 05-03, 05-04, 05-07, 05-08, 05-09

注意,內建的遞迴過濾器不是這樣工作的。相反,它基於當前鍵,每個條目只增加一次,無論在找到有效日期之前需要檢查多少個日期。如果您將它放在堆疊的開頭或末尾,那麼這個技巧將使它的工作方式相同。

為了簡化CarbonPeriod的構建,新增了一些別名:

// "start", "since", "sinceNow":
CarbonPeriod::start('2017-03-10') == CarbonPeriod::create()->setStartDate('2017-03-10');
// Same with optional boolean argument $inclusive to change the option about include/exclude start date:
CarbonPeriod::start('2017-03-10', true) == CarbonPeriod::create()->setStartDate('2017-03-10', true);
// "end", "until", "untilNow":
CarbonPeriod::end('2017-03-20') == CarbonPeriod::create()->setEndDate('2017-03-20');
// Same with optional boolean argument $inclusive to change the option about include/exclude end date:
CarbonPeriod::end('2017-03-20', true) == CarbonPeriod::create()->setEndDate('2017-03-20', true);
// "dates", "between":
CarbonPeriod::dates(..., ...) == CarbonPeriod::create()->setDates(..., ...);
// "recurrences", "times":
CarbonPeriod::recurrences(5) == CarbonPeriod::create()->setRecurrences(5);
// "options":
CarbonPeriod::options(...) == CarbonPeriod::create()->setOptions(...);
// "toggle":
CarbonPeriod::toggle(..., true) == CarbonPeriod::create()->toggleOptions(..., true);
// "filter", "push":
CarbonPeriod::filter(...) == CarbonPeriod::create()->addFilter(...);
// "prepend":
CarbonPeriod::prepend(...) == CarbonPeriod::create()->prependFilter(...);
// "filters":
CarbonPeriod::filters(...) == CarbonPeriod::create()->setFilters(...);
// "interval", "each", "every", "step", "stepBy":
CarbonPeriod::interval(...) == CarbonPeriod::create()->setDateInterval(...);
// "invert":
CarbonPeriod::invert() == CarbonPeriod::create()->invertDateInterval();
// "year", "months", "month", "weeks", "week", "days", "dayz", "day",
// "hours", "hour", "minutes", "minute", "seconds", "second":
CarbonPeriod::hours(5) == CarbonPeriod::create()->setDateInterval(new CarbonInterval::hours(5));

可以很容易地將CarbonPeriod轉換為人類可讀的字串和ISO 8601規範:

$period = CarbonPeriod::create('2000-01-01 12:00', '3 days 12 hours', '2000-01-15 12:00');
echo $period->toString();            // Every 3 days 12 hours from 2000-01-01 12:00:00 to 2000-01-15 12:00:00
echo $period->toIso8601String();     // 2000-01-01T12:00:00-05:00/P3DT12H/2000-01-15T12:00:00-05:00

 

英文原檔:

翻譯有問題的地方還請斧正~


 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/3034/viewspace-2805458/,如需轉載,請註明出處,否則將追究法律責任。

相關文章