How to format Unix timestamp into a readable date and time format in AnQiCMS template?

Calendar 👁️ 75

In website content management, time information plays a crucial role, whether it is the publication date of articles, update time, or the submission moment of comments, the record of time is indispensable.Databases usually store time data in a concise and efficient format - Unix timestamps.However, for the end user, a sequence of numbers as a timestamp is obviously less intuitive than

AnQiCMS as a content management system based on the Go language, fully considers this requirement.It provides powerful and flexible tools in the template that can easily convert Unix timestamps into various readable date and time formats, greatly enhancing the friendliness and user experience of the website content.

AnQiCMS template and timestamp

The AnQiCMS template engine syntax is very similar to Django templates, which allows partners familiar with web development to quickly get started.Its design philosophy lies in simplicity and efficiency, making content operation and template creation easy.stampToDateUsed to format Unix timestamp directly in the front-end template.

Let's briefly understand the Unix timestamp.It is usually an integer representing the number of seconds elapsed since the "epoch" (January 1, 1970, 00:00:00 UTC).1678886400This number may represent a specific date and time, but looking at the number alone, it is difficult to immediately understand its meaning.

UsestampToDateFormat the tag

stampToDateThe tag is the core tool for formatting Unix timestamps in AnQiCMS templates. Its usage is intuitive and powerful:

{{stampToDate(时间戳, "格式")}}

There are two key parts:

  • timestampThe Unix timestamp you want to format, which is usually a 10-digit integer representing the number of seconds.
  • FormatThis is a string that defines the specific format you want the time to be displayed in.

It is noteworthy that the date and time formatting string of AnQiCMS template follows the specific rules of the Go language, it uses a fixed "reference time"2006年01月02日 15时04分05秒 -0700 MSTTo define various components of time. This is different from the common pattern letters in other languages (such as PHP'sY-m-dor Python's%-Y-%m-%d).

To help you understand and apply, the following are some common reference elements for Go language formatting:

  • 2006Represents the year
  • 01Represents the month (two digits)
  • 02Represents the date (two digits)
  • 15Represent hour (24-hour format, two digits)
  • 03Represent hour (12-hour format, two digits)
  • 04Represent minutes (two digits)
  • 05Represent seconds (two digits)
  • MonRepresent the day of the week (abbreviation)
  • MondayRepresent the full name of the day of the week
  • JanRepresent the abbreviated month
  • JanuaryRepresent the full month

You can combine these reference elements to form any date and time format you need.

Common formatting examples:

  • "2006-01-02": Display as年-月-日(For example:)2023-10-27)
  • "2006/01/02": Display as年/月/日(For example:)2023/10/27)
  • "15:04:05": Display as时:分:秒(For example:)14:30:59)
  • "2006-01-02 15:04": Display as年-月-日 时:分(For example:)2023-10-27 14:30)
  • "2006年01月02日 15时04分": Display as a custom Chinese format (For example:)2023年10月27日 14时30分)
  • "Monday, Jan 02 2006": Display as星期几, 月份简写 日 年份(For example:)Friday, Oct 27 2023)

Actual application in AnQiCMS template

In AnQiCMS, the creation time of the article (CreatedTime), and Update time (UpdatedTimeAll fields are stored as Unix timestamps. You can use them on article list pages, article detail pages, or any place where you need to display these times.stampToDate.

1. Display the publish time and update time in the article list:

Assuming you are building an article list page, you want to clearly display the publish and update time of each article.

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        <div class="article-item">
            <h2><a href="{{item.Link}}">{{item.Title}}</a></h2>
            <p class="article-meta">
                发布于:<time datetime="{{stampToDate(item.CreatedTime, "2006-01-02T15:04:05Z")}}">{{stampToDate(item.CreatedTime, "2006年01月02日")}}</time>
                {% if item.CreatedTime != item.UpdatedTime %} {# 仅在更新时间与发布时间不同时显示 #}
                <br>更新于:<time datetime="{{stampToDate(item.UpdatedTime, "2006-01-02T15:04:05Z")}}">{{stampToDate(item.UpdatedTime, "2006-01-02 15:04")}}</time>
                {% endif %}
            </p>
            <p>{{item.Description}}</p>
        </div>
    {% endfor %}
{% endarchiveList %}

In the above example,CreatedTimeandUpdatedTimeFormatted into a Chinese date that is easy to read and a concise datetime format. At the same time, we also made use of HTML5's<time>tags and theirdatetimeProperty, provides machine-readable time format for search engines and accessible reading.

2. Display detailed time information on the article detail page:

On the article detail page, you may need more precise or include time information with the day of the week.

{% archiveDetail detail %}
    <article>
        <h1>{{detail.Title}}</h1>
        <p class="article-info">
            发布时间:{{stampToDate(detail.CreatedTime, "2006年01月02日 星期一 15:04:05")}}
        </p>
        {% if detail.CreatedTime != detail.UpdatedTime %}
        <p class="article-info">
            最近更新:{{stampToDate(detail.UpdatedTime, "2006年01月02日 星期一 15时04分")}}
        </p>
        {% endif %}
        <div class="article-content">
            {{detail.Content|safe}}
        </div>
    </article>
{% endarchiveDetail %}

Here, we demonstrate a more detailed date format that includes "Monday".

3. Formatting custom timestamp variables:

If you have defined or obtained a Unix timestamp variable from a template, you can also use itstampToDateto format.

{% set eventTimestamp = 1678886400 %} {# 假设这是一个活动开始的Unix时间戳 #}
<p>活动开始:{{stampToDate(eventTimestamp, "2006.01.02 下午03:04")}}</p>

This example shows how to format a custom variable and uses different time display methods (3:04 PM).

Summary

BystampToDateTags, AnQiCMS provides powerful and flexible timestamp formatting capabilities for template developers.The key is to understand the unique 'reference time' formatting rules of the Go language and to combine the corresponding format strings according to your specific needs.This makes it easy to display the original time data from the backend on a user-friendly frontend interface, thereby improving the readability of website content and the user experience.


Frequently Asked Questions (FAQ)

  1. WhystampToDateThe format of the string looks so strange, for example '2006-01-02' instead of 'YYYY-MM-DD'??This is mainly because the template engine of AnQiCMS is developed based on Go language, and Go language chooses a fixed "reference time" when designing its date and time formatting (2006-01-02 15:04:05 -0700 MST) represents the components of dates and times.You need to match the time format you want to display with this reference time.

Related articles

How to remove specific characters or extra spaces from AnQiCMS template variables?

In website content operations, we often encounter such situations: the template variable content retrieved from the database may contain some unnecessary characters, extra spaces, or formats that are not satisfactory.These subtle details, if not handled properly, may affect the aesthetics of the page, user experience, and even cause interference with search engine optimization (SEO).AnQiCMS provides powerful template filtering functionality, helping us easily clean and format these variables.The template syntax of AnQiCMS is similar to Django engine

2025-11-08

How to count the number of times a certain keyword appears in the article content in the AnQiCMS template?

In content operation, understanding the frequency of keywords in articles is an important part of SEO optimization and content strategy analysis.By counting the frequency of keywords, we can better evaluate the density, relevance, and even discover potential optimization spaces.AnQiCMS provides a powerful and flexible template system,配合 its built-in content filter, we can easily count the number of occurrences of specific keywords in the article content.### Understanding the need: Why do we need to count keywords?Count the number of times a keyword appears in an article, mainly including the following practical application scenarios: 1.

2025-11-08

How to determine if a string or array in the AnQiCMS template contains a specific keyword?

In Anqi CMS template development and daily content operation, we often encounter the need to dynamically display information based on specific attributes or keywords of the content.To achieve personalized content recommendation, emphasize the specific theme of an article, or control the display of page elements based on certain indicators in the data, accurately determining whether a string or array contains specific keywords is a very practical skill.The Anqi CMS template system adopts a syntax similar to the Django template engine, built-in with rich filters and tags, which can help us easily implement such judgments. Next

2025-11-08

How to achieve text centering or left-right alignment formatting in templates for AnQiCMS?

In web design, the layout and alignment of content are key elements of user experience.No matter if you want to center the title or align the paragraph text to the left, AnQiCMS provides a flexible template mechanism, combined with standard Web technology, which can easily meet these needs.AnQiCMS as a content management system developed based on the Go language has its core advantages in providing efficient, customizable content management and data output.It uses a syntax similar to the Django template engine, allowing you to combine system data (such as article titles, content, etc.) with

2025-11-08

What are the differences and applicable scenarios between the `default` and `default_if_none` filters when the template variable is empty?

In AnQi CMS template design, reasonably handling variables that may be empty is the key to ensuring the integrity and smooth user experience of website content display.When a template variable has no value or is in an 'empty' state, we usually do not want blank or error messages to appear on the page, but rather we would like to display a preset default content.At this time, the `default` and `default_if_none` filters provided by Anqicms come into play.They can all provide default values for variables

2025-11-08

In AnQiCMS template, how to determine if one number can be evenly divided by another to achieve conditional display?

In Anqi CMS template development, we often need to display content based on specific conditions, such as adding a special style to every few elements in a list or inserting separators at specific positions.When this condition is to determine whether a number can be divided by another number, Anqi CMS provides a concise and efficient solution with its powerful template engine.The Anqi CMS template system uses a syntax similar to the Django template engine, which makes it very intuitive in handling such logical judgments.To determine if a number can be evenly divided by another number

2025-11-08

How to quickly view the detailed structure and value of complex variables during debugging in AnQiCMS template?

During AnQiCMS template development, we often need to understand what data and structure a variable contains internally, especially when dealing with complex data objects or debugging template issues.Sometimes, direct output of a variable can only yield a simple value or error message, and cannot delve into its detailed composition.At this point, it is particularly important to master some effective methods for viewing the complete structure and value of variables.### The Challenge of AnQiCMS Template Debugging The template syntax of AnQiCMS is versatile, whether it is the system built-in `archive`

2025-11-08

The `escape` and `escapejs` filters in AnQiCMS are applicable to which HTML/JS escaping scenarios?

In AnQiCMS template development, it is very important to understand and properly use escape filters to ensure website security and correct content display.The system uses a template engine syntax similar to Django, which means it takes some security measures by default when handling variable output.Today, let's talk about the `escape` and `escapejs` filters to see in which scenarios they can be used.

2025-11-08