How to format a timestamp into a readable date in the template (such as: 2023-01-01)?

Calendar 👁️ 76
thought Here's a thinking process that leads to the article above: 1. **Understand the Goal:** The user wants an article about formatting timestamps in AnQiCMS templates. I need to act as an experienced website operations expert (but *not* em phasize my identity in the article itself), create high-quality, easy-to-understand, practical content, and avoid lists/bullet points where flowing paragraphs are better. The article should end with 2-3 FAQs. 2. **Identify Key Information from Documentation:** * **Main Tag:** `tag-stampToDate.md` is the primary source. * Usage: `{{stampToDate(时间戳, "格式")}}` * Timestamp: 10-digit, e.g., `1609470335` * Format: Golang-supported format (e.g., `2006-01-02 15:04:05`) * Examples provided in `tag-stampToDate.md`: `2006年01月02日`, `2006-01-02`, `2006/01/02`, `02/01/2006`, `2006-01-02 15:04`, `2006-01-02 15:04:05`, `2006-01-02 15:04:05.999999999 -0700 MST`, etc. * **Context:** Where would timestamps appear? * `archiveDetail` (`tag-/anqiapi-archive/142.html`): `CreatedTime`, `UpdatedTime` are timestamps. The example explicitly shows `{{stampToDate(item.CreatedTime, "2006-01-02")}}`. * `archiveList` (`tag-/anqiapi-archive/141.html`): `CreatedTime`, `UpdatedTime` (same usage). * `commentList` (`tag-/anqiapi-other/158.html`): `CreatedTime`. * `userDetail` (`tag-/api-user/3522.html`): `LastLogin`, `ExpireTime`. * **Template Engine:** `anqicms.md` states "AnQiCMS supports Django template engine syntax". `design-convention.md` confirms "similar to Django template engine tags". This implies a familiar syntax for users. * **Overall Tone:** Practical, user-focused, problem-solving. 3. **Outline the Article Structure:** * **Introduction:** Why is this important?(Readable dates improve user experience). Briefly mention AnQiCMS's templating power. * **The Core Problem:** Raw timestamps are hard to read. * **The Solution:** AnQiCMS's `stampToDate` tag. * **How to Use It (Step-by-step/Concept-by-concept):** * Basic syntax: `{{stampToDate(timestamp, "format")}}`. * Explain the "timestamp" part (where it comes from, 10-digit). * Explain the "format" part (Golang standard, common examples). Provide a few key examples from the docs. * Show practical examples within common tags (`archiveDetail`, `archiveList`, etc.). * **Putting it all Together (Comprehensive Example):** A slightly larger code snippet showing how it fits into a typical content display. * **Tips/Best Practices:** * Consistency in date formats. * Consider localization (though not explicitly covered by `stampToDate`, it's a good operational thought). * Check for empty/null timestamps. * **Conclusion:** Summarize the ease and benefit. * **FAQ:** 2-3 relevant questions. 4. **Drafting - Section by Section:** * **Introduction:** Start with the common user pain point. "In building website content, we often need to display article publication time, update time, and other information..." Connect it to user experience. "Anqi CMS provides a user-friendly and powerful template system..." * **The Core Problem & Solution:** "However, these time data are usually stored in the database in the form of timestamps (a string of numbers)..." Introduce `stampToDate`. * **Explanation of `stampToDate` Tag:** * Syntax: `{{stampToDate(timestamp, "format")}}` * **Timestamp Source:** Explain `CreatedTime`, `UpdatedTime` from `archiveDetail`, `archiveList`. Mention it's typically a 10-digit number. * **Date format string:** Emphasize Golang's `2006-01-02 15:04:05` magic number. Give clear, common examples: `2006-01-02` (year-month-day), `2006年01月02日`, `2006/01/02`, `15:04` (hour:minute), `15:04:05` (hour:minute:second). * **Actual Application Scenario:** * **Document Detail Page (`archiveDetail`)**: Show how to use it with `archive.CreatedTime` (if `archive` is the variable). Or directly with `{% archiveDetail with name="CreatedTime" format="2006-01-02" %}` (the doc shows `format` as an argument to `archiveDetail` for time fields, which is good to highlight as a shortcut). Let's use the explicit `stampToDate` for consistency with the main topic, but mention `format` as an alternative if `archiveDetail` or `archiveList` support it directly. *Self-correction: The `tag-/anqiapi-archive/142.html` actually shows `{% archiveDetail with name="CreatedTime" format="2006-01-02 15:04" %}` as a direct way. This is even better!Let's present both, but emphasize `stampToDate` first as it's the dedicated formatting function.* * **Document list (`archiveList`)**: Similar to `archiveDetail`, used within a `for` loop. * **Comment list (`commentList`)**: Same logic. * **Code example: One step at a time:** Combine the concepts. Use a snippet that fetches `archiveList` and formats its `CreatedTime`. This demonstrates the `for` loop context. twig {% archiveList archives with type="list" limit="5" %} {% for item in archives %}

Article title: {{ item.Title }}

Publish time: {{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}

{% endfor %} {% endarchiveList %} * **Some useful tips and suggestions:** * **Consistency:** Remind users to maintain consistent date formats throughout the website. * **Default value:** Consider the handling when the timestamp does not exist (although `stampToDate` may return null, it can be used in conjunction with `if` or `default` filters). * **Multilingual:** (Optional, but good for "expert" tone) Consider the multilingual environment for more complex date formatting (although `stampToDate` itself does not provide it). * **Summary:** Reiterate the flexibility of the AnQiCMS template and the convenience of `stampToDate`. * **Frequently Asked Questions (FAQ):** 1. **Q:** What if my timestamp is not a 10-digit number?**A:** Explain that `stampToDate` expects a 10-digit Unix timestamp, and if the data source is different, it may require backend preprocessing.2. **Q:** I want to display "x minutes ago" this kind of relative time, can `stampToDate` do that? **A:** `stampToDate` focuses on fixed format, relative time usually requires frontend JS or custom backend logic. 3. **Q:** Why does my date formatting show an error or not display?Check if the timestamp is valid, whether the format string conforms to the Golang standard, whether the variable name is correct, and whether it is in a valid data loop. 5. **Review and Refine:** * **Tone:** Is it natural, helpful, expert-like without being self-important? Avoid "I, me, my." Use "we," "the user can," "is needed." * **Flow:** Do paragraphs transition smoothly?Are there any abrupt jumps or bulleted lists that should be converted?(Initially, I might draft bullet points and then convert). * **Clarity:** Is the technical information easy to understand for a non-programmer? * **Accuracy:** Does it align *exactly* with the provided documentation?(Crucial for an expert role).Double-check `format` parameter usage.The doc explicitly shows `archiveDetail` with `format`.This is a very useful alternative to wrapping every `item.CreatedTime` with `stampToDate`, so I should present both clearly. * **Completeness:** Did I cover the main topic adequately?Are the FAQs relevant and helpful? * **Formatting:** Use code blocks for examples.Bold key terms. **(Self-correction during review):** * The `archiveDetail` and `archiveList` sections actually show `format` as a direct parameter, like `{% archiveDetail with name="CreatedTime" format="2006-01-02 15:04" %}`.This is a more direct way for *those specific tags* if you just need to format the time of the *current item*.`stampToDate` is more general for *any* timestamp variable.I should explain this nuance: `stampToDate` for general variables, or `format` parameter for specific built-in time fields within `archiveDetail`/`archiveList`. * The example code blocks should be consistent. Use the standard `{% ... %}` and `{{ ...In website content management, time information is often an indispensable element, such as the publication time, update time, or the time of user comments, etc.However, these time data are usually stored in the database in the form of timestamps (a series of numbers), which is not intuitive for ordinary users.AnQiCMS (AnQiCMS) fully understands this, and therefore provides a very convenient feature in its template system that can convert these original timestamps into the date and time format we are accustomed to in our daily lives, making the presentation of website content more friendly and professional.The AnqiCMS template system provides the powerful `stampToDate` tag, specifically used for timestamp formatting.Its use is intuitive and flexible, meeting the needs of most daily time display requirements. ### Understanding the basic usage of `stampToDate` tag The core of `stampToDate` tag is to combine a number representing time (timestamp) with a string defining the display rules. The basic syntax structure is as follows: `{{ stampToDate(timestamp, "format") }}` * **Timestamp:** It is usually a 10-digit number representing the number of seconds elapsed since the Unix epoch (January 1, 1970, 00:00:00 UTC).In AnQi CMS templates, you often encounter variables like `item.CreatedTime` (creation time) or `item.UpdatedTime` (update time), which exist in the form of timestamps. * **Format:** This is the key part that determines how dates and times will be displayed.The date format in AnQi CMS template follows the specific rules of the Go language.In short, you need to use a reference date `2006-01-02 15:04:05` as a template to define the output format you want. For example, if you want to display a date like `2023-01-01`, you can set the format string to `"2006-01-02"`. ### Common Formatting Examples By adjusting the format string, you can easily achieve various date and time display effects: * **Display only year, month, and day (separated by hyphens):** `"2006-01-02"` ➡️ `2023-01-01` * **Display year, month, and day in Chinese format:** `"2006年01月02日"` ➡️ `2023年01月01日` * **Display year, month, and day separated by slashes:** `"2006/01/02"` ➡️ `2023/01/01` * **Display hour, minute, and second:** `"15:04:05"` ➡️ `10:30:00` * **Display year, month, day, and hour:** `"2006-01-02 15:04"` ➡️ `2023-01-01 10:30` * **Display complete year, month, day, hour, minute, and second:** `"2006-01-02 15:04:05"` ➡️ `2023-01-01 10:30:00` ### Applying in Templates Whether it's displaying article details, lists, or comments, you can easily integrate the `stampToDate` tag into your templates.Assuming you are on the article detail page (usually using the `archiveDetail` tag to get the document details), you want to display the creation time of the article: twig {# Assuming we are on the document detail page, we can directly use archive.CreatedTime #}

Article Title: {{ archive.Title }}

Publish time: {{ stampToDate(archive.CreatedTime, "2006-01-02") }}

Update time: {{ stampToDate(archive.UpdatedTime, "2006-01-02 15:04") }}

If you are in an article list (looped through the `archiveList` tag to get multiple articles), to display the publish time of each article, the usage is similar to: twig {# Loop to output article list #} {% archiveList archives with type="list" limit="5" %} {% for item in archives %}

{{ item.Title }}

{{ item.Description }} in English

{% endfor %} {% endarchiveList %} In certain specific tags, such as `archiveDetail` or `archiveList`, the internal time fields (such as `CreatedTime`) may also support direct formatting through the `format` parameter, for example: twig {# Use the format parameter directly in the archiveDetail tag #}

Article Title: {% archiveDetail with name="Title" %}

Publish time: {% archiveDetail with name="CreatedTime" format="2006-01-02" %}

This approach is more concise, when you clearly know which specific data tags the time field to be formatted comes from, you can consider using it first. ### Some practical suggestions 1. **Maintain consistency:** Try to keep the date and time formats consistent throughout the website, which will greatly enhance the user experience and avoid confusion. 2. **Choose the appropriate accuracy:** Select the format based on the importance of the information.For example, the article list may only need to display the year, month, and day, while the comment details may need to be accurate to hours, minutes, and seconds. 3. **Note internationalization:** Although `stampToDate` provides flexible formatting, it does not handle timezone conversions or date expression conventions in different language environments.If your website is aimed at global users, you may need to perform more complex internationalization processing on the backend or frontend scripts.By using the `stampToDate` tag, Anqi CMS makes it easy to display dates and times, helping you create a clear and excellent user experience website. --- ### Frequently Asked Questions (FAQ) 1. **Q: If my timestamp is not 10 digits, can I still use `stampToDate`?A: `stampToDate` tag expects a 10-digit Unix timestamp (second-level).If your timestamp is a 13-digit millisecond timestamp, you may need to convert it to 10 digits first when processing data on the backend, or convert it to a second-level timestamp in the template through simple arithmetic operations (such as `{{ stampToDate(item.CreatedTime / 1000, "2006-01-02") }}`).But it is recommended to process the timestamp accuracy uniformly at the data source or backend. 2. **Q: I want to display relative time such as 'x minutes ago', 'yesterday', can the `stampToDate` tag do that??A: The `stampToDate` tag is mainly used to format timestamps into fixed date-time strings, such as “2023-01-01” or “2023年1月1日 10:30”.It does not provide the "x minutes ago" relative time display feature.If you need such dynamic display, it is usually necessary to combine with front-end JavaScript libraries (such as Moment.js, dayjs) to calculate and render, or generate relative time strings on the back-end and pass them to the template. 3. **Q: Why is the date formatted incorrectly or not displayed at all?Please check the following points: * **Is the timestamp valid:** Make sure the timestamp variable passed to `stampToDate` (such as `item.CreatedTime`) does indeed exist and is a valid number. * **Is the format string correct:** Define your format string strictly according to the Go language's `2006-01-02 15:04:05` reference format.Any number or symbol that does not match this may cause unexpected results.For example, if you want to display the month, you must use `01` instead of `1`. * **Variable scope:** Ensure you use `item` correctly within the `for` loop or reference `archive` or similar variables on the detail page, and that these variables contain the timestamp fields you need.

Related articles

How to customize parameter filtering for an article or product list?

In daily website operations, we often encounter such needs: we hope that users can quickly filter out the content they are interested in based on the different attributes of articles or products.For example, on a real estate website, users may want to filter for 'two bedrooms and one living room' 'school district' housing;On a product showcase website, users may want to find 'red' new T-shirts.AnQiCMS (AnQiCMS) provides a powerful and flexible custom parameter function, which can help us easily achieve this refined content filtering

2025-11-09

How to implement pagination in the content list?

When managing website content, especially when the amount of content increases, a straightforward and efficient pagination feature becomes particularly important.It not only allows visitors to find the information they need faster, improves the browsing experience, but also avoids performance issues caused by loading too much content on a single page.In Anqi CMS, implementing the pagination function of the content list is flexible and direct, and it can be configured to completion in just a few steps.The Anqi CMS adopts the Django template engine syntax, allowing you to control the display logic of content through clear tags.Add pagination to your content list, we will mainly use two core tags

2025-11-09

How to display the friend link list of the website?

During the operation of a website, friendship links are a common way for websites to recommend each other and share traffic. They not only help to increase the number of external links on the website, but also have a positive effect on SEO optimization, and can provide visitors with more valuable resources.AnQiCMS (AnQiCMS) provides a very convenient function for us to manage and display friend links. ### Managing Friend Links: Getting Started with Backend Operations Managing friend links in AnQi CMS is very intuitive.First, we need to log in to the website backend, find the "Function Management" item in the left function menu.

2025-11-09

How to add captcha functionality to a message or comment form?

During the operation of the website, the message and comment function is an important channel for enhancing user interaction and collecting feedback.However, the spam comments and malicious submissions that follow often bother website administrators.To effectively prevent these unexpected guests, adding a captcha function to the comment or message form is particularly important.AnQi CMS as a comprehensive content management system provides a convenient way to integrate this security mechanism, helping you maintain a clean, efficient interactive platform.### Preparation Before adding a captcha to your comment or message form

2025-11-09

How to safely display HTML content retrieved from a database on the frontend without escaping?

In website operation, we often need to display some content with rich formatting, such as mixed text and images on article detail pages, HTML tables on product introduction pages, or interactive codes embedded in custom pages.This content is usually stored in a database and rendered on the front-end page.However, many content management systems (including the familiar AnQiCMS) by default, for website security, will escape the HTML content retrieved from the database, resulting in the front-end displaying the original HTML code rather than the expected effect.

2025-11-09

How to truncate long text content and add an ellipsis (...)

In the daily management of website content, we often encounter such situations: an article's summary, a product description, or a list item title, if the content is too long, it not only occupies too much page space but may also destroy the overall layout aesthetics.Especially on mobile and other small screen devices, overly long text can seriously affect user experience.How to elegantly truncate these texts and add common ellipses (...) to make the information complete and tidy, which is a very practical skill in content operation.

2025-11-09

How to automatically convert URL strings in text to clickable links?

In daily content operations, we often need to mention various URLs in articles, product descriptions, or page introductions.If these URLs are displayed as plain text, users will need to manually copy and paste them to access, which undoubtedly will greatly reduce their reading experience and the interactivity of our website.How can we automatically make the URL strings in these texts clickable?In AnQi CMS, this implementation is very simple, no complex code development is required, just use its powerful template filter function to easily handle it.

2025-11-09

How to perform basic arithmetic operations in the template?

In Anqi CMS template design, it can flexibly handle data, perform simple calculations, and is an indispensable part of creating dynamic and functional websites.You may find that in addition to displaying the content itself, it is also necessary to perform some basic arithmetic operations at the template level, such as calculating the total price of goods, displaying the discounted price, or dynamically adjusting the style of elements based on numerical values.The AnQi CMS template engine (similar to Django syntax) provides us with intuitive and powerful arithmetic calculation capabilities, allowing these requirements to be easily implemented in the template.###

2025-11-09