How to format and display timestamps as readable dates or times in templates?

Calendar 👁️ 79

In the daily operation of Anqi CMS, we often need to handle various data, among which time information is undoubtedly the most common and most important category.Whether it is the publication date of the article, the update time, or the specific moment of user comments, these time data are usually stored in the form of timestamps.However, the original timestamp is not intuitive for ordinary users; they are more like a string of meaningless numbers.It is crucial to convert these timestamps into a date or time format that is easy to understand at this time.

The AnQi CMS template system, which adopts syntax similar to the Django template engine, provides us with powerful flexibility to control the display of content. Among them, the built-in tool for handling timestamps is the onestampToDateThe tag helps us easily convert a 10-digit timestamp obtained from the background into various readable date and time formats.

Understanding timestamps and time data in AnQi CMS.

In Anqi CMS, you may encounter timestamps in many places. For example, when you usearchiveDetailtags to get article details, orarchiveListtags to get the article list,CreatedTime(creation time) andUpdatedTimeThe field of (update time) defaults to returning all 10-digit timestamps. Similarly, incommentListto get the comments in theCreatedTimeor throughuserDetailTags retrieve users' information.LastLogin(recent login time) andExpireTimeWhen the VIP expires, timestamps will also be obtained.

These timestamps are typically the number of seconds elapsed since the Unix epoch (January 1, 1970, 00:00:00 UTC). Although convenient for machine reading, they are not easy for the human eye to read.1675910400These numbers are far less2023年02月09日or今天上午10:30intuitive.

stampToDateLabel: Magic of Time Formatting

To convert these timestamps into the format we are familiar with, Anqi CMS provides{{stampToDate(时间戳, "格式")}}This is the usage. The key is the second parameter - the 'format' string.The time formatting of Anqi CMS (developed based on Go language) follows the unique rules of Go language itself, which is not common.Y-m-d H:i:sinstead of using2006-01-02 15:04:05This fixed reference time is used to define the format.

It looks a bit strange, but once you master the rules, you will find it very intuitive:

  • 2006Represents the year (YYYY)
  • 01Represent month (MM)
  • 02Represent date (DD)
  • 15Represent hour in 24-hour format (HH)
  • 04Represent minutes (MM)
  • 05Represent seconds (SS)
  • MonAbbreviation for the day of the week (e.g., Mon, Tue)
  • MondayFull name of the day of the week
  • JanuaryAbbreviation for month (e.g., Jan, Feb)
  • JanuaryFull name of the month
  • MSTor-0700Represent time zone information

Just replace the datetime format you want to display2006-01-02 15:04:05As the corresponding number or letter in the position.

For example, if you want to format the timestamp as “February 09, 2023”:{{stampToDate(时间戳, "2006年01月02日")}}

If you need to display as "2023/02/09 10:30":{{stampToDate(时间戳, "2006/01/02 15:04")}}

Or more detailedly as "2023-02-09 Thursday 10:30:00":{{stampToDate(时间戳, "2006-01-02 星期一 15:04:05")}}

Remember that each number and letter in the format string has a specific meaning and must be strictly followed2006-01-02 15:04:05Construct this "magic number" accordingly

Apply in the template

Now, let's see how to apply in the actual Anqi CMS templatestampToDate.

Suppose you are creating an article list page and want to display the publication date of each article:

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
    <article>
        <h2><a href="{{ item.Link }}">{{ item.Title }}</a></h2>
        <p>
            发布于:<span>{{ stampToDate(item.CreatedTime, "2006年01月02日") }}</span>
            阅读量:<span>{{ item.Views }}</span>
        </p>
        <p>{{ item.Description|truncatechars:100 }}</p>
    </article>
    {% endfor %}
{% endarchiveList %}

In this example,item.CreatedTimeIt will output the original timestamp, andstampToDate(item.CreatedTime, "2006年01月02日")then it will be converted into a friendly format like “February 09, 2023”.

For example, on the article detail page, you may need to display more precise publication and update times:

<article>
    <h1>{{ archive.Title }}</h1>
    <div class="meta-info">
        <span>发布时间:{{ stampToDate(archive.CreatedTime, "2006-01-02 15:04:05") }}</span>
        {% if archive.CreatedTime != archive.UpdatedTime %}
            <span>最后更新:{{ stampToDate(archive.UpdatedTime, "2006年01月02日 星期一 15点04分") }}</span>
        {% endif %}
        <span>浏览量:{{ archive.Views }}</span>
    </div>
    <div class="content">
        {{ archive.Content|safe }}
    </div>
</article>

Here, we not only formatted the publication time, but also through judgmentCreatedTimeandUpdatedTimeWhether different decides whether to display the update time and format it into a Chinese style that includes the week information.

Tips for formatting timestamps.

  • Maintain consistency:The time display format of the entire website should be consistent to provide a good user experience.
  • Consider the target audience:Choose the date and time format that best suits your website's main user group. For example, websites targeting international users may need a more standardizedYYYY-MM-DDFormat, while Chinese users are more accustomedYYYY年MM月DD日.
  • Testing is crucial:Test your time display on different browsers and devices, ensuring that it can be displayed correctly in all cases.
  • Consult the official Go language documentation:If you need more complex or uncommon formats, you can refer to the official Go language documentationtimeInclude the documentation, understand all supported formatting strings, and customize the display to meet your needs.

MasteredstampToDateTags and time formatting rules in Go language allow you to easily convert timestamp data in Anqi CMS into dates and times that users love and find easy to read, thereby greatly enhancing the professionalism and user-friendliness of website content.


Frequently Asked Questions (FAQ)

Q1: I used{{stampToDate(item.CreatedTime, "YYYY-MM-DD")}}Why is the result displayed incorrectly? A1:This is because AnQi CMS follows the time formatting rules of the Go language, it does not useYYYY-MM-DDThis common format, rather than using2006-01-02As a reference. You should modify the format string to"2006-01-02"To display the year-month-date correctly. Please refer to it strictly.2006-01-02 15:04:05This fixed value is used to construct your format string.

Q2: Besides the creation/update time of the article, where else do we need to usestampToDateto format the timestamp? A2:Do you have in your comment list(commentListlabel'sCreatedTime)User details(userDetaillabel'sLastLogin/ExpireTimeTimestamps obtained in these scenarios, too, are in timestamp format. In these places, you can usestampToDatetags for formatting to provide a more friendly display.

Q3: How do I write the template code to only display the current year? A3:Anqi CMS provides a{% now "2006" %}The tag can directly obtain the current year. If you want to format an existing timestamp to only display the year, you can use{{stampToDate(时间戳, "2006")}}For example,{{stampToDate(item.CreatedTime, "2006")}}It will display the year of the article's publication.

Related articles

How to implement the switching display of multilingual website content?

In today's globalized digital environment, making a website support multiple language display is no longer an option, but a necessity for many enterprises and content operators to expand international markets and improve user experience.AnQiCMS (AnQiCMS) took this into consideration from the very beginning, integrating powerful multilingual support features to help us easily switch between different language displays on the website.How can we specifically operate to enable multilingual content switching capabilities for our Anqi CMS website?This can mainly be found in the system language package

2025-11-08

How to display and manage the display of images and video multimedia resources?

In website operation, high-quality multimedia content is the key to attracting visitors and improving user experience.AnQiCMS (AnQiCMS) is well-versed in this, providing comprehensive features to help users easily manage and flexibly display images and videos on their websites.From unified resource library to intelligent optimization settings, AnQiCMS makes multimedia management efficient and convenient. ### One, Core Multimedia Management Center: Image Resource Management Anqi CMS gathers all uploaded images and video resources into a centralized "Image Resource Management" module.This is not only the place where you store your materials

2025-11-08

How to display single page content on the front end of a website (such as About Us, Contact Us)?

In website operation, single-page content like "About Us" and "Contact Us" is indispensable, as it carries important functions such as displaying corporate image, providing contact information, or stating service terms.For friends using AnQiCMS, it is actually a very direct and flexible thing to beautifully display these single-page contents on the website front end. ### Single Page Content Management Overview Firstly, we need to create and manage these single pages in the AnQiCMS backend system.In the left navigation bar of the background, you can find the "Page Resources" menu

2025-11-07

How to display extra field data under a custom content model in Anqi CMS?

In AnQi CMS, the flexibility of the content model is one of the highlights of the project, allowing us to create and manage various content structures according to the actual business needs.Whether it is an article, product, event, or any other information that requires a specific field to describe, it can be easily realized through a custom content model.After adding exclusive additional fields to these models, the next step naturally is how to accurately and beautifully display this valuable data on the website front-end.This is not a complex task, Anqi CMS provides intuitive and convenient template tags to complete it

2025-11-07

How to implement pagination display of content lists in AnQi CMS?

In Anqi CMS, the pagination display of the content list is one of the key functions to enhance user experience, optimize website performance, and facilitate content management.AnQi CMS, with its flexible template tags and powerful content management capabilities, provides us with a simple and efficient way to meet this requirement.### The Importance of Pagination in Content Lists Imagine if your website had thousands of articles, products, or comments all displayed on one page. Not only would this make the page load incredibly slowly, but it would also cause users to get lost in the sea of information.

2025-11-08

How to display the website's friend link list on the front end?

In website operation, friendship links play an indispensable role.They not only help improve the quality of a website's external links, enhance search engine optimization (SEO) effects, but also bring additional traffic to the website and increase its credibility through peer recommendations.Our CMS understands the importance of friendship links, therefore, it provides an intuitive and convenient management function, and supports flexible front-end display methods, allowing website administrators to easily present these important cooperative resources on the page.### One, Friendship Link Management in AnQi CMS In the AnQi CMS backend management interface

2025-11-08

how to display the captcha in the message or comment function?

In website operation, the message and comment functions are important channels for interaction with users, but they often become hotbeds of spam and malicious flooding.It is particularly important to add captcha to these interactive functions to maintain a clean and high-quality communication environment.AnQi CMS understands this and provides a convenient solution for it.How can you display a captcha in the Anqi CMS message or comment feature to effectively resist spam?This mainly consists of two core steps: first, enable the captcha feature in the background, and then integrate the captcha element into the front-end template.### Step 1

2025-11-08

How to display the user message or article comment list and handle the review status?

In website operation, user comments and article reviews are an important part of promoting interaction and enhancing content value.For users of Anqi CMS, it is crucial to display user-generated content reasonably and manage their review status effectively to ensure the quality of website content and user experience.We will discuss in detail how to achieve this goal in Anqi CMS. ### Learn about comment and message management in Anqi CMS Anqi CMS provides users with convenient content comment and website message management features.In the background management interface

2025-11-08