* 1.6.0-DEV
+ * added a date function to ease date comparison
* fixed unary operators precedence
* 1.5.1 (2012-01-05)
--- /dev/null
+``date``
+========
+
+.. versionadded:: 1.6
+ The date function has been added in Twig 1.6.
+
+Converts an argument to a date to allow date comparison:
+
+.. code-block:: jinja
+
+ {% if date(user.created_at) < date('+2days') %}
+ {# do something #}
+ {% endif %}
+
+The argument must be in a format supported by the `date`_ function.
+
+You can pass a timezone as the second argument:
+
+.. code-block:: jinja
+
+ {% if date(user.created_at) < date('+2days', 'Europe/Paris') %}
+ {# do something #}
+ {% endif %}
+
+If no argument is passed, the function returns the current date:
+
+.. code-block:: jinja
+
+ {% if date(user.created_at) < date() %}
+ {# always! #}
+ {% endif %}
+
+.. _`date`: http://www.php.net/date
'constant' => new Twig_Function_Function('constant'),
'cycle' => new Twig_Function_Function('twig_cycle'),
'random' => new Twig_Function_Function('twig_random'),
+ 'date' => new Twig_Function_Function('twig_date_converter'),
);
}
return $date->format($format);
}
- // convert to a DateTime
+ return twig_date_converter($date, $timezone)->format($format);
+}
+
+function twig_date_converter($date = null, $timezone = null)
+{
+ if ($date instanceof DateTime) {
+ return $date;
+ }
+
$asString = (string) $date;
+
if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1)))) {
$date = new DateTime('@'.$date);
$date->setTimezone(new DateTimeZone(date_default_timezone_get()));
$date->setTimezone($timezone);
}
- return $date->format($format);
+ return $date;
}
/**
--- /dev/null
+--TEST--
+"date" function
+--TEMPLATE--
+{{ date() == date('now') ? 'OK' : 'KO' }}
+{{ date() > date('-1day') ? 'OK' : 'KO' }}
+{{ date(date1) == date('2010-10-04 13:45') ? 'OK' : 'KO' }}
+{{ date(date2) == date('2010-10-04 13:45') ? 'OK' : 'KO' }}
+{{ date(date3) == date('2010-10-04 13:45') ? 'OK' : 'KO' }}
+{{ date(date4) == date('2010-10-04 13:45') ? 'OK' : 'KO' }}
+--DATA--
+date_default_timezone_set('UTC');
+return array(
+ 'date1' => mktime(13, 45, 0, 10, 4, 2010),
+ 'date2' => new DateTime('2010-10-04 13:45'),
+ 'date3' => '2010-10-04 13:45',
+ 'date4' => 1286199900,
+ 'date5' => -86410,
+)
+--EXPECT--
+OK
+OK
+OK
+OK
+OK
+OK