added a date function to ease date comparison (closes #571)

This commit is contained in:
Fabien Potencier
2012-01-06 20:31:06 +01:00
parent c07014a387
commit 764829f55a
5 changed files with 72 additions and 2 deletions
+1
View File
@@ -1,5 +1,6 @@
* 1.6.0-DEV
* added a date function to ease date comparison
* fixed unary operators precedence
* 1.5.1 (2012-01-05)
+33
View File
@@ -0,0 +1,33 @@
``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
+1
View File
@@ -12,3 +12,4 @@ Functions
block
parent
dump
date
+12 -2
View File
@@ -156,6 +156,7 @@ class Twig_Extension_Core extends Twig_Extension
'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'),
);
}
@@ -325,8 +326,17 @@ function twig_date_format_filter(Twig_Environment $env, $date, $format = null, $
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()));
@@ -343,7 +353,7 @@ function twig_date_format_filter(Twig_Environment $env, $date, $format = null, $
$date->setTimezone($timezone);
}
return $date->format($format);
return $date;
}
/**
@@ -0,0 +1,25 @@
--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