`date` filter: How to format a GoLang `time.Time` type into a specific date string?

Calendar 👁️ 80

In AnQi CMS template development, flexibly displaying dates and times is an indispensable part of content presentation. You may often need to format date information in the system or content, such as年-月-日Hello World月/日 时:分Presented in various ways to users. At this point,dateThe filter becomes your helpful assistant.

AnQi CMS is an enterprise-level content management system built with Go language, and naturally follows some conventions of GoLang in handling date and time in the template level.dateThe filter is specifically designed to process GoLang nativetime.Timetype data.

Get to knowdateThe filter and its GoLang formatting rules

dateThe main function of the filter is to transform atime.TimeThe value, formatted as a string as defined by you, should be converted to an easily readable date-time string. But there is an important detail to note:dateThe filter only acceptstime.TimeType data as input.

The formatting of strings is unique to GoLang,“2006-01-02 15:04:05Base time layout.This is not a random sequence of numbers, but a reference time point used internally by the Go language to define date and time formats.

  • 2006: denotes the year
  • 01: denotes the month (with leading zero)
  • 02: denotes the date (with leading zero)
  • 15Hours (24-hour format, with leading zero)
  • 04Minutes (with leading zero)
  • 05Seconds (with leading zero)
  • You can freely combine these numbers and symbols to create any date and time format you want. For example:
    • 2006-01-02It will output.年-月-日
    • 01/02It will output.月/日
    • 15:04It will output.时:分
    • Mon, 02 Jan 2006 15:04:05 MSTIt will output.星期一, 02 1月 2006 15:04:05 CSTThis is a complete format

How to usedateFilter

When your template variable directly holds GoLang'stime.Timeobject, usedatethe filter is very intuitive. Suppose you have defined a filter in your GoLang backend code.currentTimeSet the variable and make it current.time.TimePass the object to the template:

{# 假设 currentTime 是一个 GoLang 的 time.Time 对象 #}

{# 仅显示年份 #}
<div>当前年份:{{ currentTime|date:"2006" }}</div>

{# 显示年-月-日 #}
<div>完整日期:{{ currentTime|date:"2006-01-02" }}</div>

{# 显示月/日 时:分 #}
<div>简要时间:{{ currentTime|date:"01/02 15:04" }}</div>

{# 显示中文格式的日期时间 #}
<div>中文格式:{{ currentTime|date:"2006年01月02日 星期一 15时04分" }}</div>

Key points:time.TimeDistinguish from timestamps.

In AnQi CMS template development, you will often encounter the need to display the content publication time (CreatedTime) or update time (UpdatedTime) These fields are usually in thearchiveDetail/archiveListorcategoryDetail tags, usually in the timestampThe form provided, not directtime.TimeType.

If you pass these timestamps directly todateA filter, the template engine will report an error due to type mismatch. In this case, Anqi CMS provides another convenient tag specifically for formatting timestamps -stampToDate.

stampToDateThe usage of tags is as follows:

{# 假设 item.CreatedTime 是一个时间戳(例如:1675862400) #}

{# 格式化时间戳为“年-月-日” #}
<div>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</div>

{# 格式化时间戳为“年年年年/月月/日日 时:分:秒” #}
<div>更新时间:{{ stampToDate(item.UpdatedTime, "2006/01/02 15:04:05") }}</div>

{# 格式化为更友好的中文形式 #}
<div>内容创建于:{{ stampToDate(item.CreatedTime, "2006年01月02日 15点04分") }}</div>

You can clearly see through the above examplesdateFilters andstampToDateEach label applies to a specific scenario. Correctly distinguishing between these data types and their corresponding processing methods can help you develop templates more efficiently and avoid unnecessary errors.

Summary

dateThe filter is used to process GoLang natively in the Anqi CMS templatetime.TimeThe standard way of formatting data types.It is based on the unique GoLang time format layout, providing high flexibility. timestampRemember to use when handling datastampToDateTo complete the formatting, make sure the template runs correctly and displays the data. Mastering these two tools will allow you to easily handle various date and time display needs.


Frequently Asked Questions (FAQ)

1. Why myCreatedTimeUse the field directly.dateThe filter will report an error?

This is usually becauseCreatedTimeThe field is in the content tag of AnQi CMS (such asarchiveList/archiveDetailetc.), and is returned in the form of timestamp rather than GoLang'stime.TimeObject.dateThe filter requires the input to betime.Timeof type. For timestamps, you should usestampToDatetags for formatting, for example:{{ stampToDate(item.CreatedTime, "2006-01-02") }}.

2. Why is the time formatting string of GoLang '2006-01-02 15:04:05'? Are there any other memory methods?

The GoLang date time formatting string is designed by its creator to avoid ambiguity, each number and symbol represents a specific date and time element. Remember it is1月2日周一下午3点04分05秒MST 2006年(Monday, January 2 15:04:05 MST 2006),You can use each element of this string as a replacement template. For example, if you want the year, write “2006Enter the month you want01Enter the hour you want15This helps you quickly build the required format.

3. Can I create in custom GoLang backend codetime.TimeObject and pass it to the template, then usedatefilter?

Of course you can. If you are doing a second development and have created it in your GoLang backend logic,time.TimeA type variable, you can directly pass it to the Anqi CMS template. In the template, this variable can be used directlydateFormatted by the filter. This isdateOne of the most typical use cases of the filter, it perfectly connects the GoLang backend logic and the frontend template's date and time display.

Related articles

How to convert a numeric string to an integer or floating-point number type in AnQiCMS template?

In AnQiCMS template development, we often encounter situations where we need to handle various types of data.Sometimes, data obtained from a database or through user input, even if they represent numbers, may be treated as strings at the template layer.In this case, if direct mathematical operations or numerical comparisons are performed on these 'number strings', unexpected results or even errors may occur.Therefore, understanding how to convert a numeric string to an integer or floating-point number type in the AnQiCMS template is crucial for ensuring the accuracy of data processing and the correctness of logic

2025-11-08

The role of `escape` and `escapejs` filters in preventing XSS attacks or handling special characters?

In website content operation, the display method and security of the content are equally important.AnQi CMS is an efficient content management system that provides comprehensive considerations for website security, among which the `escape` and `escapejs` filters are important tools for us to combat network attacks and ensure the correct display of content.Understanding their role can help us better manage and publish content.

2025-11-08

The `safe` filter: when to use, what potential security risks need to be paid special attention to?

During the template development process of Anqi CMS, the way content is displayed is flexible and diverse, and one of the very important filters is `safe`. Understanding the working principle of the `safe` filter, when to use it, and the security considerations it may bring, is crucial for building a website that is both functional and secure. ### The core function of the `safe` filter First, let's understand a basic security mechanism of the Anqi CMS template engine: the default automatic escaping.

2025-11-08

How to safely display rich text content containing HTML tags in AnQiCMS templates?

In website operation, we often need to display text content containing rich formats and interactive elements, which is what we usually call rich text.This content may contain bold, italic, links, images, and even tables with HTML tags.How can one ensure that these HTML tags are rendered correctly in the AnQiCMS template while also taking into account the website's security, which is a topic worth discussing.### Understand the default security mechanism of AnQiCMS template Firstly, we need to understand one of the core security designs of the AnQiCMS template system: by default

2025-11-08

The `stampToDate` filter: How to format Unix timestamp in AnQiCMS template?

In AnQiCMS template design, the way data is displayed is crucial to user experience.Especially information such as dates and times, if presented in raw Unix timestamp format, is difficult for ordinary visitors to understand.Fortunately, AnQiCMS provides a very practical filter——`stampToDate`, which can help us easily convert these machine-readable number sequences into clear and friendly date and time formats.### Understand Unix Timestamp and `stampToDate` Filter First

2025-11-08

The `floatformat` filter: how to precisely control the decimal places of floating-point number display?

In website content management, we often need to display various numbers, especially floating-point numbers with decimal points.The way numbers are displayed, whether it is product prices, statistics, or calculation results, directly affects user experience and the accuracy of information.Inconsistent or inaccurate decimal places may cause the page to look cluttered, and even lead to misunderstandings in financial or precise measurement situations.

2025-11-08

How `forloop.Counter` and `forloop.Revcounter` assist in indexing operations during template loops?

In AnQiCMS template development, we often need to handle various data lists, such as article lists, product displays, or navigation menus.The `for` loop is the core tool for traversing these lists.However, simply listing data items often does not meet all needs, we may also need to know the current item being traversed in the list is which item, or how many items are left until the end of the list.

2025-11-08

`capfirst`, `lower`, `upper`, `title` filters: how to handle the need for English text case conversion?

In website content operation, the uniformity and beauty of text format are crucial for improving user experience.Especially when dealing with English text, flexibly controlling the case can help us better present information, whether it is used for headings, keywords, or body content.AnQiCMS provides a series of practical template filters to help you easily deal with various English case conversion needs.

2025-11-08