How to convert timestamp data stored in the background into a readable date and time format for display?

Calendar 👁️ 71

When managing website content in Anqi CMS, we often encounter situations where we need to display dates and times.However, the time information stored in the background database is usually in the form of timestamps, which is very efficient for machine processing, but difficult for users to read directly.For example, you might see a string like1609470335Such a number represents a specific moment, but we would like it to be displayed in a more friendly format like '2021 January 1 12:25:35'.

Lucky enough, Anqi CMS fully considers this need, providing a very convenient and powerful template tag, which helps us easily convert timestamp data from the backend into an easily understandable date and time format.

Get to know the core tools:stampToDateTag

The template system of AnqiCMS is built-in with a namedstampToDatetag, which is specifically used for formatting timestamp displays. Its basic usage is very intuitive:

{{ stampToDate(时间戳变量, "格式字符串") }}

The "timestamp variable" is the sequence of numbers you get from the backend (usually a 10-digit Unix timestamp), and the "format string" is the style you want the date and time to appear in.

An important concept needs to be understood: The format string of AnQi CMS follows the Go language's time formatting standard. Go language uses a fixed reference date2006-01-02 15:04:05Use it as a formatting template. This means that if you want to display the year, use2006; to display the month, use01; to display the date, use02For example. At first glance, this may seem counterintuitive, but once you get the hang of it, you'll find it very flexible.

Common date and time format examples

To help you better understand and apply, let's look at some common formatting examples, assuming our timestamp variable isitem.CreatedTimeIts value is1609470335(That is January 1, 2021, 12:25:35):

  1. Only display the date (year-month-date)If you only care about the publication date of the article and do not want to see the specific time, you can use the following format:

    {{ stampToDate(item.CreatedTime, "2006-01-02") }}
    {# 输出: 2021-01-01 #}
    
  2. Display the full date and timeIf you need to be accurate to seconds, you can use:

    {{ stampToDate(item.CreatedTime, "2006-01-02 15:04:05") }}
    {# 输出: 2021-01-01 12:25:35 #}
    
  3. Custom Chinese formatFor Chinese websites, we may want to display the words 'Year, Month, Day':

    {{ stampToDate(item.CreatedTime, "2006年01月02日 15时04分") }}
    {# 输出: 2021年01月01日 12时25分 #}
    
  4. Other common formatsYou can also combine various formats as needed:

    • Display the month and date:{{ stampToDate(item.CreatedTime, "01-02") }}(Output: 01-01)
    • Show time (hour:minute):{{ stampToDate(item.CreatedTime, "15:04") }}(Output: 12:25)
    • Show the day of the week:{{ stampToDate(item.CreatedTime, "Mon") }}or{{ stampToDate(item.CreatedTime, "Monday") }}(Output: Fri or Friday)
    • Show time with AM/PM:{{ stampToDate(item.CreatedTime, "3:04PM") }}(Output: 12:25PM)

The key is to remember2006-01-02 15:04:05This reference date indicates what each number and symbol represents, and then replace it with the actual characters you want. For example, if you want to display the year, write2006; To display a hyphen-Then write-.

Where is the timestamp used in AnQi CMS?

The AnQi CMS backend stores timestamp data in many places, for example:

  • Article/Document Management: Article publication time (CreatedTime), and Update time (UpdatedTime).
  • Comment Management: Time of comment posting (CreatedTime).
  • User management: Time of the last login (LastLogin) and VIP expiration time (ExpireTime).

These timestamps are usually used in loopsitemThe attribute of the object, or as the current object's attribute passed to the template on the detail page. For example, in the article list loop, you will use{{item.CreatedTime}}to get the publication timestamp of each article.

Application scenario: Format the publish time of the article list

Suppose you are editing an article list template (for example/template/default/archive/list.html), and you want to display the publish date of each article:

{# 假设这里是文章列表循环的开始 #}
{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
    <li>
        <h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
        <div>
            {# 这里是格式化时间戳的关键 #}
            <span>发布日期:{{ stampToDate(item.CreatedTime, "2006年01月02日") }}</span>
            <span>浏览量:{{item.Views}} 次</span>
        </div>
        <p>{{item.Description}}</p>
    </li>
    {% empty %}
    <li>暂无文章内容。</li>
    {% endfor %}
{% endarchiveList %}
{# 假设这里是文章列表循环的结束 #}

Through this simple line of code, all article timestamps will be automatically converted to the easy-to-read format of "XXXX year XX month XX day", greatly enhancing the user experience of the website.

Summary

Converting the timestamp data in the background to a readable date and time format is a basic but important task in content operation. Anqicms providesstampToDateLabel, through its flexible Go language formatting mechanism, makes this process simple and efficient. Just remember that magical2006-01-02 15:04:05Refer to the date, you can freely customize any date and time display format you want, making your website content more贴近用户亲近。

Frequently Asked Questions (FAQ)

1. Why is string formatting2006-01-02 15:04:05such number combinations instead of commonYYYY-MM-DD?

This is the time formatting convention unique to the Go language (the underlying development language of AnQi CMS).It is not a simple placeholder, but a specific date and time chosen at the birth of the Go language as a 'reference template'.When you provide2006-01-02 15:04:05When, the Go language will convert your timestamp to the corresponding date and time parts according to this template structure. So, if you want to display the year, just write2006If you want to display the specific month, day, hour, minute, and second, use them separately.01/02/15/04/05As a template. This method may need to adapt at first, but once you understand its logic, you will find it very flexible and precise.

2. I can use it directly.dateDoes the filter format timestamps?

It is not recommended to use it directlydateThe filter formats timestamps. AnQi CMS template provides onedateThe filter, but it expects an input written in Go programming language.time.TimeAn object type, not the raw Unix timestamp number. If you use the timestamp directlydateA filter may cause errors or results that do not meet expectations. Therefore, for timestamp data obtained from the background, please make sure to use a specialstampToDatetag for formatting

Related articles

How to format user input plain text content (including newline characters) into HTML paragraphs and newline characters for display?

In website content management, we often encounter such needs: when users input a block of plain text content in the background, it often contains some natural paragraphs and line breaks. We hope that these paragraphs and line breaks are rendered correctly on the website front-end as HTML paragraph tags (`<p>`) and line break tags (`<br/>`), rather than being compressed into a blob or ignored by the browser.AnQi CMS provides a very convenient and powerful template filter to solve this problem, allowing plain text content to be presented elegantly on the web.

2025-11-08

How to extract a part of a long string or HTML content and display an ellipsis at the end?

In website content operation, we often encounter such situations: the article list page needs to display the summary of the content, the product detail page needs to show a brief introduction, or in some special modules, we need to extract a part of the long text or content containing HTML tags, and add "..." at the end to prompt the user that the content is not complete.This not only effectively saves page space and keeps the layout neat, but also improves the reading experience and attracts users to click to view the full content.To achieve such a function, if it were to be manually截取 each time, it would undoubtedly consume a lot of time and effort.Fortunately

2025-11-08

How to safely output content containing HTML tags in a template and prevent them from being escaped by the browser?

In website operation, we often need to display information with rich formatting and media content, such as carefully edited article details, product introductions, or customized pages.This content often contains HTML tags, such as image tags `<img>`, link tags `<a>`, paragraph tags `<p>` and so on.However, if you directly output this content to a web page, you may find that it does not render as expected, but rather displays the HTML tags as plain text, greatly affecting the user experience and the beauty of the page.

2025-11-08

How to implement multi-condition filtering on a product list or article list page and display the filtered results?

In a content management system, providing users with flexible multi-condition filtering functions is a key factor in improving website usability and user experience.Whether it is an e-commerce website product list or a content portal article classification page, users hope to quickly locate the content they are interested in.AnQiCMS (AnQiCMS) with its powerful content model and template tag system allows you to easily meet this requirement and intuitively display the filtered results. ### 1.Establishing the foundation: defining content models and custom fields All filtering functions rely on data.

2025-11-08

How to concatenate the elements of an array into a string separated by a specified delimiter for display?

When managing and displaying content in Anqi CMS, we often encounter situations where we need to merge a group of related information into a coherent text.For example, a product may have many characteristics, and we hope to display the list of these characteristics uniformly with commas or slashes.Or perhaps, an article is associated with multiple keyword tags, and we want to summarize these tags into a single line of text.At this time, the powerful template filter of Anqi CMS can be put to good use, especially the `join` filter, which can help us easily achieve this goal.### Understand the `join` filter

2025-11-08

How to perform basic arithmetic operations on numbers in templates and display the results?

In website operation, we often need to dynamically display some numerical information, such as total product price, percentage of article reading, discounted price, and so on.The template system provided by AnQi CMS is powerful, it adopts syntax similar to the Django template engine, allowing us to easily implement these requirements when displaying content, perform basic arithmetic operations directly in the template, and display the results.### Master basic arithmetic operations in templates The most direct way to write arithmetic expressions in Anqi CMS templates is within double curly braces `{{ }}`

2025-11-08

How to generate random placeholder text to simulate real content display during template development?

During the process of website template development, we often encounter a challenge: how to fill the page to check the layout, style, and responsiveness before the real content is ready?If the template is empty or only has a few lines of simple text, it is difficult to evaluate the design effect directly.This is a very useful technique for generating random placeholder text. AnQiCMS (AnQiCMS) is an efficient and customizable content management system that fully considers the needs of template developers at this stage.

2025-11-08

How to ensure that a captcha is displayed when users submit comments or messages to prevent robot abuse?

When operating a website, we often encounter bots submitting a large number of spam messages or comments, which not only affects the quality of the website content but also increases the management burden and may have a negative impact on the reputation of the website.Luckily, AnQiCMS provides an in-built captcha mechanism that can effectively help us prevent such abusive behaviors.Next, let's see how to add a captcha for user comments or reviews in AnQiCMS.

2025-11-08