How to format a 10-digit timestamp retrieved from the database into a custom date-time format in AnQiCMS template?

Calendar 👁️ 75

In website content display, we often encounter time data from the database that is a long string of numbers, such as1678886400. This string of numbers, which is what we commonly call a timestamp, is very convenient for computers, but it seems cold and difficult to understand for users visiting websites.Fortunately, AnQi CMS provides us with a very convenient feature that can easily convert these original 10-digit timestamps into the date and time format we are accustomed to reading.

Get to knowstampToDateFormatting tag

The template engine of AnQi CMS (which adopts the syntax similar to Django template engine) is built in a namedstampToDateThe tag is specifically used for formatting timestamps. Its usage is very intuitive, you just need to provide two parameters: the timestamp to be formatted.10-digit timestampand what you wantFormat string.

The basic syntax structure is like this:

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

Pay special attention to that 'format string'. It is not what we are accustomed to in our daily lives.YYYY-MM-DDThis form, but it adopts a Go language-specific 'reference time' format. Don't worry, it sounds a bit professional, but in fact it's very simple: you just need to remember2006-01-02 15:04:05This specific time is used as a standard template. By replacing the year, month, day, hour, minute, and second in this standard time, you can define any date and time display format you want.

For example:

  • If you want to displayYear-Month-DateFormat the string accordingly"2006-01-02".
  • If you want to displayYear/Month/DateFormat the string accordingly"2006/01/02".
  • If you want to displayMonth-Day Time:MinuteFormat the string accordingly"01-02 15:04".
  • If you want to displayComplete Year-Month-Day Time:Minute:SecondFormat the string accordingly"2006-01-02 15:04:05".

Remember, this2006-01-02 15:04:05It does not represent the date you will get, it is just a "template", the system will generate the final date and time based on the actual timestamp you provide and the corresponding position of this template.

Find your timestamp data in the template

In Anqi CMS templates, many time fields retrieved from the database are in the form of 10-digit timestamps by default. These fields usually haveTimesuffixes, for example:

  • The creation time of the article: archive.CreatedTime
  • The update time of the article: archive.UpdatedTime
  • The creation time of the comment: item.CreatedTime(When you are looping through the comment list)
  • and similarCreatedTimeorUpdatedTimefield.

When you are usingarchiveDetail/archiveList/commentListWhen tags are used to retrieve data, these timestamp fields will be included in the returned object, and they can be accessed directly through.symbols.

Formatting timestamps into readable dates

Now, let's takestampToDateCombine the label with the actual timestamp variable and see how it can be applied in the template:

Suppose we are displaying the details page of a document, and we need to show its publication time and update time:

<div class="article-meta">
    <p>
        发布于:{{stampToDate(archive.CreatedTime, "2006年01月02日 星期一")}}
    </p>
    <p>
        最近更新:{{stampToDate(archive.UpdatedTime, "2006/01/02 15:04:05")}}
    </p>
    <p>
        简短日期:{{stampToDate(archive.CreatedTime, "01-02")}}
    </p>
</div>

If we are iterating over a comment list, we want to display the posting time of each comment:

{% for comment in comments %}
    <div class="comment-item">
        <span class="comment-author">{{comment.UserName}}</span>
        <span class="comment-time">于 {{stampToDate(comment.CreatedTime, "2006年01月02日 15:04")}} 评论道:</span>
        <p class="comment-content">{{comment.Content}}</p>
    </div>
{% endfor %}

You can see, whether it is a single piece of data or data in a loop, as long as you get that 10-digit timestamp variable, you can use it flexiblystampToDateFormat it. This makes your website content look more professional and user-friendly.

BystampToDateThis compact and powerful tag, we can easily convert the cold timestamps in the database into user-friendly dates and times, greatly enhancing the reading experience of the website content.Mastering this skill, you can make every time information on the website come to life.


Frequently Asked Questions (FAQ)

1. Why does my timestamp formatting show an error or blank?This usually has several reasons:

  • Invalid timestamp data: Check the variable you have enteredstampToDatewhether it is indeed a valid 10-digit timestamp. If the variable is empty, 0, or any other non-numeric value, it may cause display errors. You can try using{{你的时间戳变量}}Directly output, confirm whether it is the expected number.
  • Format string error:The date format string in Go language is very strict, it must use2006-01-02 15:04:05As a reference. Any minor error (such as writing the year asYYYY) will cause formatting to fail. Please carefully refer to the format in the document.
  • Timestamp digit is incorrect: stampToDateThe label expects to receive a 10-digit (second-level) timestamp. If it is a 13-digit (millisecond-level) timestamp, you need to divide it by 1000 first.

2. Can I customize the format, such as showing the day of the week or morning/afternoon?Of course. The date format string in Go language is very powerful, supporting many different formatting options, including days of the week, AM/PM, etc. For example:

  • Show the day of the week:"Mon Jan _2 15:04:05 2006"ofMonAbbreviation for the day of the week,MondayThe full name of the day of the week.
  • Show AM/PM:"3:04PM"ofPMIt can display AM/PM. You can refer totag-stampToDate.mdMore examples provided in the document, try to combine the format you need.

3. Are all time fields 10-digit timestamps? How do I know if a field is a timestamp?In Anqi CMS, it is usually named withTimesuffix fields (such asCreatedTime,UpdatedTime,LastLoginare stored in the form of 10-digit timestamps. If you are unsure of the specific data type of a field, you can try using the template.{{你的字段变量|dump}}This filter. It will output the detailed type and value of the variable, helping you confirm whether it is a timestamp. IfdumpThe result shows thatint64Or similar integer types, and values that look like timestamps can be usedstampToDateto format.

Related articles

How to set a default friendly display value for a possibly empty variable in AnQiCMS template?

When building website templates, we often encounter situations where a variable may be empty in the template due to unentered data, optional fields left blank, or specific business logic.If these empty variables are not processed, the front-end page of the website may appear blank areas, display unfriendly placeholders, and even cause layout errors, thereby affecting user experience and the professionalism of the website.

2025-11-07

What is the correct syntax for using the `{{ obj|filter__name:param }}` filter in AnQiCMS templates?

AnQiCMS (AnQiCMS) provides strong support for content operations with its efficient and flexible features.In daily content display, we often need to process and format data in a fine-grained manner to ensure that information is presented to visitors in a **state**.At this moment, the 'filter' in the template has become an indispensable tool for us. Today, let's delve into the correct syntax for using filters in Anqi CMS templates: `{{ obj|filter_name:param }}`.Understand and master it

2025-11-07

How to quickly remove spaces or specific characters from both ends, left or right of a string in AnQiCMS template?

In content management, we often encounter situations where there are excessive spaces or unwanted specific characters at both ends of strings, which not only affects the display aesthetics of the content, but also sometimes causes unnecessary interference to data processing or search engine optimization (SEO).AnQiCMS uses a template engine syntax similar to Django, providing us with concise and efficient filters (Filters) to easily solve these problems.This article will introduce how to quickly remove spaces or specific characters from both ends, left, or right of a string in the AnQiCMS template.

2025-11-07

How to implement capitalizing the first letter of each word in the article title in AnQiCMS templates?

In website content operation, the standardization of article titles is often a key factor in improving the professionalism and user experience of the website.A neat and consistent title format not only makes the content more attractive but also helps improve the overall image of the website.AnqiCMS provides us with a very concise and efficient solution, which can easily capitalize the first letter of each word in the article title with a simple filter in the template.

2025-11-07

What are the main differences between AnQiCMS's `date` and `stampToDate` filters when handling date data?

In AnQiCMS template development, displaying time data is an indispensable part, whether it is the publication time of articles, the update date of products, or the time records of user behavior, it needs to be presented to the user in a clear and readable manner.To meet the different time processing needs, AnQiCMS provides two core filters: `date` and `stampToDate`.

2025-11-07

How to always display product prices (floating point numbers) with two decimal places in AnQiCMS templates?

When operating a product display website, you may often encounter situations where you need to display product prices accurately.A professional and user-friendly website often requires a unified display format for product prices, such as always retaining two decimal places, even for integer prices, which are automatically filled with `.00`. AnQiCMS with its flexible template system makes these details handling very convenient.

2025-11-07

How does AnQiCMS automatically identify URLs or email addresses in text and convert them into clickable hyperlinks?

In the daily operation of websites, we often need to add various links in article content, such as URLs pointing to external resources, or email addresses for easy reader contact.Manually adding hyperlinks one by one is not only inefficient but also prone to errors.Fortunately, AnQiCMS provides very practical features that can intelligently identify URLs and email addresses in text and automatically convert them into clickable hyperlinks, greatly enhancing the efficiency and user experience of content editing.

2025-11-07

How to control the truncation length of the hyperlink text when using the AnQiCMS `urlizetrunc` filter?

In website content operation, we often need to display various hyperlinks in articles, comments, or list pages.These links may be pointing to other content within the site, external resources, or the contact email of the user.However, some excessively long links may not only destroy the page layout, affect the aesthetics, but may also reduce the user's reading experience.Especially in limited display space, long URLs can make content look disorganized.

2025-11-07