How to format a Unix timestamp into a readable date and time string?

Calendar 👁️ 88

In website content management, the way time is presented is crucial to user experience.Although the system may prefer a unified and efficient Unix timestamp format in the background processing, for visitors, a string of irregular numbers is obviously not as intuitive and easy to understand as Anqi CMS knows this and provides a simple yet powerful tool to solve this problem.

Unix timestamp: 'Time language' in the database

A Unix timestamp is simply the number of seconds that have elapsed since midnight on January 1, 1970 (UTC/GMT).It is a globally unified time representation that does not change with regions and time zones, which is very suitable for database storage, data transmission, and programming calculations.In Anqi CMS, the article's publish time (CreatedTime)、Update Time(UpdatedTime), even the user's login records or VIP expiration time are usually stored in this numeric form.

However, when these timestamps are directly presented on the website's front end, they will only be a series of numbers, for example1678886400This display is meaningless to ordinary users, and no date or time information can be obtained from it.

The solution of Anqi CMS:stampToDateTag

To make these numbers 'speak', Anqi CMS provides a namedstampToDateThe template tag, which can easily convert Unix timestamps to any readable date and time format you need.

The basic usage of this tag is very intuitive:{{stampToDate(时间戳, "格式")}}

Here:

  • 时间戳: Is the Unix timestamp you want to convert, which is usually 10 digits. In Anqi CMS templates, it is usually going to beitem.CreatedTime/archive.UpdatedTimeVariables
  • 格式This is a string that defines the format you want the date and time to be displayed in.

Understand the time formatting rules of Go language

stampToDateThe core of the label lies in its second parameter-the date and time format string. Anqi CMS is developed based on Go language, so its time formatting follows the unique rules of Go language rather than commonY-m-d H:i:soryyyy-MM-dd HH:mm:ss.

Go language uses a fixed reference time2006-01-02 15:04:05As a formatted template. You just need to replace the year, month, day, hour, minute, second, and other elements in this reference time with the display style you want.

For example:

  • If you want to displayYear-Month-Datethen the format string is"2006-01-02".
  • If you want to displayYear/Month/Datethen the format string is"2006/01/02".
  • If you want to displayYear Month Day (Chinese)then the format string is"2006年01月02日".
  • If you want to displayHour:Minute:Secondthen the format string is"15:04:05".
  • If you want to displayYear-Month-Date Hour:Minutethen the format string is"2006-01-02 15:04".

You can also combine these elements, even add other characters, such as days of the week or AM/PM, and Go language will intelligently parse and output according to the template you define.

Sample application: Format document publish time in template

Assuming you are building a list of articles page and want to display the publication time of the articles in the format of "Year-Month-Day Hour:Minute". This is usually involved in the Anqi CMS template.archiveListorarchiveDetail.

A common use case is to display the publishing time of an article:

{# 在一个文章列表循环中 #}
{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
    <li>
        <a href="{{item.Link}}">
            <h5>{{item.Title}}</h5>
            <div>
                <span>发布于:{{stampToDate(item.CreatedTime, "2006年01月02日 15:04")}}</span>
                <span>更新于:{{stampToDate(item.UpdatedTime, "2006-01-02 15:04:05")}}</span>
            </div>
        </a>
    </li>
    {% endfor %}
{% endarchiveList %}

In the code above,item.CreatedTimeanditem.UpdatedTimeIt is the Unix timestamp retrieved from the database. ThroughstampToDateLabels, they are converted to user-friendly date and time strings. For example, ifitem.CreatedTimeIs1678886400, it may be displayed as “March 15, 2023, 00:00”.

You can also directly format the time of the current document on the document detail page:

{# 在文档详情页中 #}
<div>
    <h1>{% archiveDetail with name="Title" %}</h1>
    <p>发布时间:{% archiveDetail archiveCreatedTime with name="CreatedTime" %}{{stampToDate(archiveCreatedTime, "2006年1月2日 下午3点04分")}}</p>
    <p>最近更新:{% archiveDetail archiveUpdatedTime with name="UpdatedTime" %}{{stampToDate(archiveUpdatedTime, "2006-01-02 15:04:05")}}</p>
</div>

This shows two different custom formats that you can choose flexibly according to the page design and user habits.

More formatting scenarios

In addition to the publication and update time of the article, there are many other scenarios in Anqi CMS that involve timestamps, such as the registration time of users, the last login time, and the expiration time of VIP members, etc. As long as you can obtain these timestamp variables, you can use them.stampToDateFormat labels.

For example, show the user's last login time:

{# 假设 userDetail 标签可以获取到用户详情 #}
{% userDetail lastLogin with name="LastLogin" id="1" %}
<p>最后登录时间:{{stampToDate(lastLogin, "2006/01/02 15:04")}}</p>

Summary

BystampToDateLabels and flexible Go language time formatting rules, Anqi CMS provides strong and easy-to-use time display control capabilities for website operators.Whether it is a list page, detail page, or other module that needs to display time information, you can convert the cold Unix timestamp into a clear and friendly date and time string according to your actual needs, thereby greatly enhancing the professionalism and user experience of the website.


Frequently Asked Questions (FAQ)

1. The Unix timestamp I provide is 13 digits long,stampToDateCan the tag handle it?CurrentlystampToDateThe tag is designed to handle the standard 10-digit Unix timestamp (second level).If your timestamp is 13 digits (millisecond level), you need to divide it by 1000 before passing it in to convert it to a 10-digit second-level timestamp. For example:{{stampToDate(item.CreatedTime / 1000, "2006-01-02")}}.

2. Are there any other tags or filters for formatting dates and times in Anqicms?The template engine of Anqicms also supports a nameddateThe filter, but it requires the value to be in Go language already.time.Timetype, not the original Unix timestamp. For Unix timestamps directly retrieved from the database,stampToDateTags are a more direct and recommended formatting method.dateFilters are more suitable for those processed by the Go backend and converted totime.Timethe variable of the object.

3. Why does Go language use time formatting2006-01-02 15:04:05Does this number serve as a reference? What is its special meaning?This is a unique feature of Go language design, which does not use placeholders like other languagesYrepresents the year,mRepresents a month), but instead chose a specific date and time as a formatting template. This date2006年1月2日 下午3点4分5秒It is a 'reference point' used in the official Go language documentation to display all time elements, each number and position represents the corresponding date and time component. For example,2006representing a four-digit year,01representing a two-digit month,02representing a two-digit date,15Represents the hour in 24-hour format, etc. Just remember this special date-time string and replace the numbers as needed to define the output format.

Related articles

Can the `divisibleby` filter be used to implement alternating row colors or other conditional styles in a loop?

In the daily operation of website content, how to make the list data more readable and visually attractive is a key factor in improving user experience.AnQiCMS (AnQiCMS) offers a flexible template engine, providing rich possibilities for content display.Today, let's talk about a very practical template filter——`divisibleby`, and see how it helps us achieve alternate row coloring or other conditional styles in loops.## Get to know the `divisibleby` filter AnQi CMS template system

2025-11-08

How to determine if a number can be evenly divided by another number in AnQiCMS templates?

In web content display, we often encounter situations where we need to adjust the layout or display logic of content based on the characteristics of some numbers.For example, we may need to insert an advertisement every few articles, or make even and odd rows of the table display different background colors, or perform special operations when the list loops to a specific position.In the AnQiCMS template system, based on the Django template engine syntax, it provides a very practical filter that can easily meet this requirement.This filter is `divisibleby`

2025-11-08

What will the `get_digit` filter return when processing non-numeric strings?

In AnQiCMS template development, we often use various filters to process data, where the `get_digit` filter is a convenient tool for extracting specific digits from numbers.However, when we turn our attention to a more common but potentially misunderstood scenario - that is, when the `get_digit` filter encounters a **non-numeric string**, its behavior becomes less obvious.Let's review the performance of the `get_digit` filter when dealing with pure numbers.When the data is of a standard numeric type

2025-11-08

How to extract a number at a specified position from a numeric string (e.g., extract the batch number from the product code)?

In the daily operation of websites, we often encounter situations where we need to handle various encodings or IDs, such as product codes, order numbers, batch numbers, etc., which often contain multiple segments of information, and we may only need to extract a part of the numbers.For example, from the complex product code “PROD20230815BATCH007”, we only want to quickly obtain the batch number “007”.The Anqi CMS, with its flexible content model and powerful template tag system, can easily meet such demands.Next, we will discuss how to use Anqi CMS

2025-11-08

What are the similarities and differences between the `stampToDate` and `date` filters in handling time formatting and their applicable scenarios?

In Anqi CMS template development, we often need to display time data in a user-friendly format.The system provides two very practical tools for handling time: the `stampToDate` function and the `date` filter.Although they can all help us format time, there are some key similarities and differences as well as applicable scenarios, understanding these can make our template development more efficient and accurate.## `stampToDate`: A timestamp handler In AnQi CMS

2025-11-08

How to truncate a long string and automatically add an ellipsis (...)?

In website operation, we often encounter situations where we need to display a piece of text, but we cannot let it be too long to avoid affecting the page layout or reading experience.Whether it is the title, abstract, or product description of an article, if the content exceeds the expected length, the usual practice is to truncate a part of it and add an ellipsis at the end to indicate that the content has not yet ended.For AnQiCMS users, achieving such an effect is not complicated, thanks to its flexible and powerful template engine, we have a variety of built-in filters (Filters) that can easily handle it

2025-11-08

How does the `truncatechars_html` filter safely truncate HTML content without breaking the tag structure?

In website operation, we often need to display an abstract of a large amount of content on a page, such as the article list on the homepage, a brief introduction on the product details page, or recommended content for a module.These summaries must be able to attract readers to click and maintain the neat and beautiful layout of the page.However, when the content itself contains rich HTML formatting (such as bold, italic, images, links, etc.), simply truncating the character length often leads to a headache: the HTML tag structure is destroyed, causing the page to display incorrectly and even affecting the overall style.Imagine

2025-11-08

How to convert the first letter or the first letter of each word in an English string to uppercase in AnQiCMS?

In daily website content management, we often need to finely control the display format of English strings, such as capitalizing the first letter of the article title or making each word of the product name start with uppercase to enhance the professionalism and unity of the content.AnQiCMS (AnQiCMS) fully understands the importance of these subtle details to the website's image, and therefore provides convenient and powerful string processing functions in template design, allowing you to easily meet these formatting needs.The Anqi CMS uses a template engine syntax similar to Django

2025-11-08