Converts an input to a DateTime instance.
<pre> {% if date(user.created_at) < date('+2days') %} {# do something #} {% endif %} </pre>
Twig_Environment $env A Twig_Environment instance:
DateTime|string $date A date:
DateTimeZone|string $timezone A timezone:
DateTime A DateTime instance
function twig_date_converter(Twig_Environment $env, $date = null, $timezone = null) {
// determine the timezone
if (!$timezone) {
$defaultTimezone = $env
->getExtension('core')
->getTimezone();
}
elseif (!$timezone instanceof DateTimeZone) {
$defaultTimezone = new DateTimeZone($timezone);
}
else {
$defaultTimezone = $timezone;
}
if ($date instanceof DateTime) {
$date = clone $date;
if (false !== $timezone) {
$date
->setTimezone($defaultTimezone);
}
return $date;
}
$asString = (string) $date;
if (ctype_digit($asString) || !empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1))) {
$date = '@' . $date;
}
$date = new DateTime($date, $defaultTimezone);
if (false !== $timezone) {
$date
->setTimezone($defaultTimezone);
}
return $date;
}