.. versionadded:: 1.1
The timezone support has been added in Twig 1.1.
+.. versionadded:: 1.5
+ The default date format support has been added in Twig 1.5.
+
The ``date`` filter formats a date to a given format:
.. code-block:: jinja
{{ post.published_at|date("m/d/Y", "Europe/Paris") }}
+If no format is provided, Twig will use the default one: ``F j, Y H:i``. This
+default can be easily changed:
+
+.. code-block:: php
+
+ $twig = new Twig_Environment($loader);
+ $twig->getExtension('core')->setDateFormat('d/m/Y');
+
.. _`date`: http://www.php.net/date
.. _`DateTime`: http://www.php.net/manual/en/datetime.construct.php
*/
class Twig_Extension_Core extends Twig_Extension
{
+ protected $dateFormat = 'F j, Y H:i';
+
+ /**
+ * Sets the default format to be used by the date filter.
+ *
+ * @param string $format The default date format string
+ */
+ public function setDateFormat($format)
+ {
+ $this->dateFormat = $format;
+ }
+
+ /**
+ * Gets the default format to be used by the date filter.
+ *
+ * @return string The default date format string
+ */
+ public function getDateFormat()
+ {
+ return $this->dateFormat;
+ }
+
/**
* Returns the token parser instance to add to the existing list.
*
{
$filters = array(
// formatting filters
- 'date' => new Twig_Filter_Function('twig_date_format_filter'),
+ 'date' => new Twig_Filter_Function('twig_date_format_filter', array('needs_environment' => true)),
'format' => new Twig_Filter_Function('sprintf'),
'replace' => new Twig_Filter_Function('strtr'),
* {{ post.published_at|date("m/d/Y") }}
* </pre>
*
+ * @param Twig_Environment $env A Twig_Environment instance
* @param DateTime|string $date A date
* @param string $format A format
* @param DateTimeZone|string $timezone A timezone
*
* @return string The formatter date
*/
-function twig_date_format_filter($date, $format = 'F j, Y H:i', $timezone = null)
+function twig_date_format_filter(Twig_Environment $env, $date, $format = null, $timezone = null)
{
+ if (null === $format) {
+ $format = $env->getExtension('core')->getDateFormat();
+ }
+
if (!$date instanceof DateTime && !$date instanceof DateInterval) {
$asString = (string) $date;
if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1)))) {
--- /dev/null
+--TEST--
+"date" filter
+--TEMPLATE--
+{{ date|date }}
+{{ date|date('d/m/Y') }}
+--DATA--
+date_default_timezone_set('UTC');
+$twig->getExtension('core')->setDateFormat('Y-m-d');
+return array(
+ 'date' => mktime(13, 45, 0, 10, 4, 2010),
+)
+--EXPECT--
+2010-10-04
+04/10/2010