Skip to main content

DateTimeMapper / DateTimeImmutableMapper

Maps an input value to a mutable DateTime object (or null).

Mappers::dateTimeImmutable() behaves identically but produces an immutable DateTimeImmutable object instead. It takes the same $mandatory, $min and $max arguments.

Accepts the following input types:

  • DateTimeInterface (DateTime or DateTimeImmutable).
  • SQL date time string (e.g. '2023-12-13 12:04:12').
  • Any Stringable object — cast to string and parsed as above.
  • null — left as null, subject to validation.

Validation possibilities​

ParameterTypeDefaultDescription
$mandatoryboolfalseRejects null input.
$minDateTimeInterfacenullRequires the value to be >= $min (inclusive).
$maxDateTimeInterfacenullRequires the value to be <= $max (inclusive).

Boundaries are inclusive: a value equal to $min or $max is valid.

Example: basic conversion​

$result = Bind::values('2023-12-13 12:04:12', null)->map(Mappers::dateTime())->toArray()->exec();
var_dump($result->get());

Output:

array(2) {
[0]=>
object(DateTime)#1 (3) {
["date"]=>
string(26) "2023-12-13 12:04:12.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
[1]=>
NULL
}

Example: mandatory and min / max boundaries​

$min = new \DateTime('2009-12-31');
$max = new \DateTimeImmutable('2010-01-02');

$result = Bind::attrs(['dateTime1' => '2009-12-30 00:00:00', 'dateTime2' => '2010-01-03 00:00:00', 'dateTime3' => null])
->props(['dateTime1', 'dateTime2', 'dateTime3'], Mappers::dateTime(true, $min, $max))
->toArray()
->exec();

// result will be invalid with error messages provided for all dateTime properties.
var_dump($result->isValid()); // false
var_dump($result->getErrorMap()->getChild('dateTime1')->isEmpty()); // false because before $min
var_dump($result->getErrorMap()->getChild('dateTime2')->isEmpty()); // false because after $max
var_dump($result->getErrorMap()->getChild('dateTime3')->isEmpty()); // false because mandatory