DateTimeMapper / DateTimeImmutableMapper
Maps an input value to a mutable DateTime object (or null).
Mappers::dateTimeImmutable()behaves identically but produces an immutableDateTimeImmutableobject instead. It takes the same$mandatory,$minand$maxarguments.
Accepts the following input types:
DateTimeInterface(DateTimeorDateTimeImmutable).- SQL date time
string(e.g.'2023-12-13 12:04:12'). - Any
Stringableobject — cast to string and parsed as above. null— left asnull, subject to validation.
Validation possibilities
| Parameter | Type | Default | Description |
|---|---|---|---|
| $mandatory | bool | false | Rejects null input. |
| $min | DateTimeInterface | null | Requires the value to be >= $min (inclusive). |
| $max | DateTimeInterface | null | Requires 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