In addition to `stampToDate`, how can the `date` filter of Anqi CMS implement custom date and time formatting when handling `time.Time` type?

Calendar 👁️ 73

In AnQi CMS, the display of dates and times often needs to be adjusted flexibly according to the actual needs of the website. We all know,stampToDateThe filter is very convenient for handling Unix timestamps, as it can easily convert a string of numeric timestamps into the date format we need. But sometimes, the date values we handle in the template may already be in a Go language'stime.TimeType object, not an original timestamp. In this case, Anqi CMS provides another powerful tool, namelydateFilter (or its aliastimeFilter, it can directly act ontime.Timeobjects to customize the format, providing more fine-grained control.

Understandingtime.Timethe source of objects in the template

While usingdateBefore the filter, we first need to clarify which data is in the template in the form oftime.TimeObjects. Usually, we get this kind of date and time objects from the following places:

  1. The system built-in tag returns the date and time field:For example, inarchiveDetailthe document addition time obtained from the tagCreatedTimeor update timeUpdatedTimeAlthough the document mentions that they are 'timestamps', in some specific scenarios or after internal processing, if they are in the form oftime.TimePass the object in the form to the template variable, and it can be used directlydatefilter.
  2. nowThe current time obtained by the tag: {% now "2006-01-02 15:04" %}This tag actually generates a formatted string. But if we want to get a processabletime.Timeobject, it is usually in the backend controller to represent the current time intime.TimeType is passed to the template or the time is directly provided as an object through some auxiliary functions (if the system provides them)time.TimeProvided.
  3. BysetTag assignment.time.TimeVariable:If you pass a variable through the context (context) in the templatesetby assigning a tagtime.Timeof a type, then it can also be processed directlydateby the filter.

It should be noted that,dateThe filter has strict requirements for the input type, itit mustreceives atime.Timeobject. If the input is a common 10-digit or 13-digit Unix timestamp (such as1678886400)dateThe filter will fail due to type mismatch. In this case, it should usestampToDatefilter.

dateFilter: Free formatting based on Go language layout

dateThe usage of the filter is very intuitive, it is withstampToDateThe biggest difference is that it does not need to convert the timestamp totime.Timean object because its input is alreadytime.Time. Its syntax is{{ 变量名 | date:"格式字符串" }}.

The format string here is a Go language-specific date and time format, which is not like PHP or JavaScriptY-m-d H:i:sThis placeholder, instead of using a fixed 'magic number'—2006-01-02 15:04:05.999999999 -0700 MSTAs a reference template. You need to replace the corresponding number in this reference template with the format you want.

Let us delve into some examples to understand better:

Assuming we have atime.TimeVariable typesmyTimeIt is worth2023年3月15日 下午3点04分05秒.

  • Display year-month-date:If you want to display2023-03-15The format string should be:"2006-01-02".

    {{ myTime | date:"2006-01-02" }}
    {# 输出: 2023-03-15 #}
    
  • Display date/month/year:If you want to display15/03/2023The format string should be:"02/01/2006".

    {{ myTime | date:"02/01/2006" }}
    {# 输出: 15/03/2023 #}
    
  • Show time (hour:minute):If you want to display15:04The format string should be:"15:04".

    {{ myTime | date:"15:04" }}
    {# 输出: 15:04 #}
    
  • Display the full date and time:If you want to display2023年03月15日 15时04分05秒The format string should be:"2006年01月02日 15时04分05秒". Go language's date formatting allows you to insert any text you want between numbers, such as 'year', 'month', 'day', 'hour', 'minute', 'second'.

    {{ myTime | date:"2006年01月02日 15时04分05秒" }}
    {# 输出: 2023年03月15日 15时04分05秒 #}
    
  • Show the day of the week and the month name:The layout of the Go language also supports displaying the day of the week (Mon, Monday) and the name of the month (Jan, January).

    {{ myTime | date:"Mon, January 2, 2006" }}
    {# 输出: Wed, March 15, 2023 #}
    

    HereMonCorresponding to Wednesday,JanuaryCorresponding to March.

Through these examples, you will find that the date formatting in the Go language may seem unique at first glance, but once you master the corresponding relationship of the 'magic numbers', it can provide great flexibility, allowing you to display dates and times in almost any format you can imagine.

Some tips for practical application

We may use it like this in content operation and template developmentdateFilter:

  • Formatting the publication time of articles:“`twig {# Assuming archive.CreatedTime is already a time.Time object #}

    Published on: {{ archive.CreatedTime | date: “January 02, 2006” }}

    Updated on: {{

Related articles

How to use the `divisibleby` filter in AnQi CMS template to achieve alternate row coloring or group output every N elements?

In website operation, a well-designed page layout and content display can significantly improve user experience and readability.Especially in scenarios with a long list of items, if all entries are presented in the same style, it is easy to cause visual fatigue.At this time, alternating line colors or grouping by a specific quantity can well solve these problems.

2025-11-08

How to use the `length_is` filter in an Anqie CMS template to validate the length of user input or data lists and return a boolean value for conditional rendering?

In Anqi CMS template development, flexibly controlling the display method of content is the key to improving website user experience.Among them, the `length_is` filter is a very practical tool that can help us easily check the length of user input or data lists in templates and conditionally render based on the check results.The core function of the `length_is` filter is to determine whether the length of a variable (whether it is a string, array, or mapping) is equal to a predefined value.It does not directly return the specific length value

2025-11-08

The `length` filter calculates the length of Chinese string in an AnQi CMS template, is it counted by bytes or characters? How does it affect the output?

In AnQi CMS template development, dealing with string length is a common requirement.When dealing with multilingual content, especially when it includes Chinese characters, how a string's length is calculated in bytes or characters can directly affect the accuracy of template output and the presentation of the content.The `length` filter used in the Anqi CMS template is designed to solve this problem.It counts the length of the string by characters rather than by bytes.This means, whether it is an English letter

2025-11-08

How to use the `get_digit` filter to extract a specific digit from a long numeric ID and display or perform logical operations in an Anqi CMS template?

In the development of Anqi CMS templates, we sometimes encounter situations where we need to extract a certain number of digits from a long numeric ID.For example, you may want to assign different styles to content based on some number of the ID, or make some logical judgments.At this time, the `get_digit` filter can be used.It provides a concise and efficient way to achieve this goal, making your template logic more flexible.

2025-11-08

How to format Unix timestamp to 'YYYY-MM-DD HH:MM' and other localized date strings using the `stampToDate` filter in AnQi CMS?

In website content management, the display of date and time information is ubiquitous.Whether it is the publication time of the article, the listing date of the product, or the submission time of the comments, a clear and readable date format is crucial for improving user experience.AnQiCMS (AnQiCMS) fully understands this need and provides powerful template tags and filters, among which the `stampToDate` filter is a powerful tool to convert the original Unix timestamp into a localized date string that we are familiar with.This article will delve into the usage of the `stampToDate` filter

2025-11-08

How to safely use the `truncatechars_html` filter in Anqi CMS template to truncate HTML rich text content and automatically close tags?

In website content operation, we often need to display the partial content of articles, products, or single pages on list pages, abstract areas, or specific blocks.This content is often rich text that includes HTML tags. Simply truncating by character count may cause the HTML tags to be cut off, thereby破坏页面布局和显示效果.For example, a `<p>This is a paragraph<strong id=“test”>bold</span>` content that is abruptly truncated may cause the page to display unclosed tags.

2025-11-08

What are the differences in the truncation logic of the `truncatewords` and `truncatechars` filters when truncating the abstract of an AnQi CMS article?

In Anqi CMS, in order to display the article summary on the list page or preview area, we often need to truncate the article content.At this time, the `truncatewords` and `truncatechars` filters come into play.They all can help us to shorten long content, but there are significant differences in the truncation logic between them, especially in handling Chinese and English characters and words, where their performance is even more disparate.Understanding these differences can help us better control the presentation of the summary.

2025-11-08

How to use `upper`, `lower`, `capfirst`, and `title` filters to unify the English title case format of the CMS frontend page?

In website operation, the professionalism and consistency of content display are crucial for improving user experience and brand image.Especially when dealing with English titles, consistent capitalization not only makes the page look neater, but also indirectly affects the readability of the content.AnQiCMS (AnQiCMS) relies on the powerful features of the Django template engine and provides several very practical filters to help us easily format the case of English titles on the front-end page.

2025-11-08