Helper functions
Since this package relies heavily on DateTimeImmutable and DateInterval objects and because it is sometimes complicated to get your hands on such objects the package comes bundled with two simple functions defined under the League\Period namespace:
- League\Period\datepoint;
- League\Period\duration;
datepoint
function League\Period\datepoint(mixed $datepoint): DateTimeImmutable;
Returns a DateTimeImmutable object or throws:
- a
TypeErrorif the submitted parameters have the wrong type. - a PHP
Exceptionif creating aDateTimeImmutablefails.
parameters
$datepointcan be:- a
DateTimeInterfaceimplementing object - a string parsable by the
DateTimeconstructor. - an integer interpreted as a timestamp.
- a
examples
Using the $datepoint argument
use function League\Period\datepoint;
datepoint('yesterday'); // returns new DateTimeImmutable('yesterday')
datepoint('2018'); // returns new DateTimeImmutable('@2018')
datepoint(2018); // returns new DateTimeImmutable('@2018')
datepoint(new DateTime('2018-10-15')); // returns new DateTimeImmutable('2018-10-15')
datepoint(new DateTimeImmutable('2018-10-15')); // returns new DateTimeImmutable('2018-10-15')
duration
function League\Period\duration(mixed $duration): DateInterval;
Converts its single input into a DateInterval object or throws a TypeError otherwise.
parameter
$duration can be:
- a
League\Period\Periodobject; - a
DateIntervalobject; - a string parsable by the
DateInterval::createFromDateStringmethod. - an integer interpreted as the interval expressed in seconds.
Examples
use League\Period\Period;
use function League\Period\duration;
duration('1 DAY'); // returns new DateInterval('P1D')
duration(2018); // returns new DateInterval('PT2018S')
duration(new DateInterval('PT1H')); // returns new DateInterval('PT1H')
duration(new Period('now', 'tomorrow'));
// returns (new DateTime('yesterday'))->diff(new DateTime('tomorrow'))