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) {
if (!$date instanceof DateTime) {
$asString = (string) $date;
if (ctype_digit($asString) || !empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1))) {
$date = new DateTime('@' . $date);
}
else {
$date = new DateTime($date);
}
}
else {
$date = clone $date;
}
// set Timezone
if (null !== $timezone) {
if ($timezone instanceof DateTimeZone) {
$date
->setTimezone($timezone);
}
else {
$date
->setTimezone(new DateTimeZone($timezone));
}
}
elseif (($timezone = $env
->getExtension('core')
->getTimezone()) instanceof DateTimeZone) {
$date
->setTimezone($timezone);
}
else {
$date
->setTimezone(new DateTimeZone(date_default_timezone_get()));
}
return $date;
}