Django's built-in template tags provide several useful tools for working with dates in templates. Here's a rundown of some common ones:
{% now %}
: This tag displays the current date and time. By default, it uses the format YEAR-MONTH-DAY HOUR:MINUTE:SECOND
, but you can customize it by providing a format string.
django{% now "Y-m-d H:i:s" %}
{{ value|date:"D d M Y" }}
: This filter formats a date according to the given format string. For example, D
represents the day of the week, d
represents the day of the month, M
represents the month name, and Y
represents the year.
django{{ some_date|date:"D d M Y" }}
{% if today.date > some_date %}
: This conditional tag allows you to compare dates. In this example, it checks if today's date is after some_date
.
django{% if today.date > some_date %} Do something {% endif %}
{% ifequal date1 date2 %}
: This conditional tag checks if two dates are equal.
django{% ifequal date1 date2 %} Do something {% endifequal %}
{% for date in date_list %}
: This loop tag allows you to iterate over a list of dates.
django{% for date in date_list %} {{ date }} {% endfor %}
{% now "U" as current_time_unix %}
: This tag allows you to get the current time in Unix timestamp format.
django{% now "U" as current_time_unix %}
{% now "Y-m-d" as current_date %}
: This tag allows you to get the current date in a specific format and store it in a variable.
django{% now "Y-m-d" as current_date %}
These are just a few examples of how you can work with dates using Django's built-in template tags. You can find more information and examples in the Django documentation: https://docs.djangoproject.com/en/stable/ref/templates/builtins/#date.