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

Calendar 👁️ 55

As an experienced CMS website operation personnel, I know that website content should not only be rich but also presented in a user-friendly manner.Time information is an important part of the content, but the timestamps (Unix timestamps) stored in the database are often just a string of numbers, which can be confusing to display directly.Therefore, formatting these timestamps into easily readable date and time strings is a key step in improving user experience and enhancing the readability of the content.

In AnQi CMS, we have a very convenient template tag to solve this problem, namelystampToDate.

Understanding timestamps in databases

The Anqi CMS stores information such as content release and update time as a 10-digit Unix timestamp. For example, you may find inarchiveListorarchiveDetailthe tag.item.CreatedTimeoritem.UpdatedTimesuch fields, their values may be similar to1609470335. This string of numbers represents the number of seconds from 00:00:00 UTC on January 1, 1970 to a certain moment. Although precise, it has no meaning to the general reader.

The solution of Anqi CMS:stampToDateTag

To make these numbers meaningful, Anqi CMS providesstampToDateTemplate tag. This tag can convert a 10-digit timestamp into a readable date and time string according to the specified format.

The use of this tag is very intuitive:

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

Among them,时间戳Which is from the database field (such asitem.CreatedTimeThe number obtained from the bracket.格式It is the style you want the date and time to be displayed in, following the unique time formatting rules of the Go language.

Deep understanding of the time formatting rules in Go language.

The time formatting rules for Go language may be different from those in other programming languages (such as PHP'sY-m-d H:i:sor Python's%Y-%m-%d %H:%M:%SThe habits are different. In Go language, string formatting is not represented by placeholders to indicate year, month, and day, but is defined by a fixed reference date and time.This reference date and time is:

2006-01-02 15:04:05

You can understand this reference date as a format “template”. When you want to output the year, just use2006; when you want to output the month, just use01; when you want to output the date, just use02and so on.

Here are some common formatting examples and their corresponding output effects:

  • Display only the date (year-month-day):
    
    {{stampToDate(item.CreatedTime, "2006-01-02")}}
    {# 示例输出: 2021-06-30 #}
    
  • Display the date (year/month/day):
    
    {{stampToDate(item.CreatedTime, "2006/01/02")}}
    {# 示例输出: 2021/06/30 #}
    
  • Show date and time (exact to minutes):
    
    {{stampToDate(item.CreatedTime, "2006-01-02 15:04")}}
    {# 示例输出: 2021-06-30 12:30 #}
    
  • Show full date and time (exact to seconds):
    
    {{stampToDate(item.CreatedTime, "2006-01-02 15:04:05")}}
    {# 示例输出: 2021-06-30 12:30:00 #}
    
  • Show only month and date:
    
    {{stampToDate(item.CreatedTime, "01-02")}}
    {# 示例输出: 06-30 #}
    
  • Show Chinese date:
    
    {{stampToDate(item.CreatedTime, "2006年01月02日")}}
    {# 示例输出: 2021年06月30日 #}
    
  • Show date with weekday:
    
    {{stampToDate(item.CreatedTime, "Mon Jan _2 2006")}}
    {# 示例输出: Wed Jun 30 2021 #}
    

You can combine them flexibly according to your actual needs2006/01/02/15/04/05And use the unique date and time string elements supported by the Go language to create unique date and time strings.

Applied in practice: Formatting document time in the template

In the Anqi CMS template, when we usearchiveListorarchiveDetailTags used to retrieve document data usually includeCreatedTime(creation time) andUpdatedTime(Update time) field. The value of these fields is a 10-digit timestamp. We can use them directly asstampToDatethe first parameter for formatting.

For example, on a document detail page, you may want to display the document's publication time:

<article>
    <h1>{{archive.Title}}</h1>
    <div class="article-meta">
        <span>发布于:{{stampToDate(archive.CreatedTime, "2006年01月02日 15:04")}}</span>
        <span>浏览量:{{archive.Views}}</span>
    </div>
    <div class="article-content">
        {{archive.Content|safe}}
    </div>
</article>

In this example,archive.CreatedTimeIt will be formatted as2021年06月30日 12:30such a string, greatly enhancing the user's understanding of time information.

Summary

BystampToDateLabel, AnQi CMS provides a powerful and flexible way to handle and display timestamp data in databases.Mastering the time formatting rules in Go language is the key to using this tag correctly. It allows you to convert cold numeric timestamps into warm, understandable date and time strings, thus optimizing your website content presentation and user experience.


Frequently Asked Questions (FAQ)

1. How should I handle the timestamp I get from the database if it is not 10 digits long but longer (e.g., 13 digits)?

10-digit timestamp usually refers to Unix timestamp (seconds), while 13-digit timestamp usually represents Unix millisecond timestamp. Anqi CMS'sstampToDateThe tag expects to receive a 10-digit Unix timestamp (seconds). If your timestamp is a 13-digit millisecond timestamp, you need to convert it tostampToDateFirst, perform a simple mathematical operation to convert it to seconds. For example, you can use division by 1000:{{stampToDate(item.MilliTimestamp / 1000, "2006-01-02 15:04:05")}}Please make sure to check your data source to confirm the actual unit of the timestamp.

2. The time formatting rules of Go language (2006-01-02 15:04:05) look strange, is there a more intuitive way to remember?

Reference date of Go language2006-01-02 15:04:05Can be decomposed into the following numbers, each representing a specific time unit:

  • 2006Represents the year
  • 01Represents the month (January)
  • 02Represents the date (2nd day)
  • 15representing the hour (3 PM, 24-hour format)
  • 04representing minutes
  • 05representing seconds

You can remember it asJanuary 2, afternoon 3:04:05, in 2006When you want to include a time unit in the format, use the corresponding number. For example, to display the year, write2006; to display the month, you write01This is a very unique formatting method that is very flexible once mastered.

3. BesidesstampToDateBesides, does Anqi CMS have other template tags related to time?

Yes, in addition to formatting the timestamps in the database, Anqi CMS also provides{% now "格式" %}tags to retrieve and format the current system time. Its formatting rules are consistent withstampToDateExactly the same, all follow the reference date format of the Go language. For example, to display the current year, you can use{% now "2006" %}This tag is often used to display the current year's copyright information in the footer, or in other places where real-time time needs to be displayed.

Related articles

How to use a `for` loop to iterate over data and handle `empty` data situations?

As an experienced CMS website operations personnel, I fully understand the importance of content in attracting and retaining users.Dynamic, responsive website content display is the key to improving user experience, and effectively handling data sets, especially when the data may be empty, is a basic skill in operation work.AnQiCMS (AnQiCMS) powerful template engine provides us with flexible tools to achieve these goals, where the `for` loop tag and its `empty` block are our powerful assistants for content display.

2025-11-06

How does the Anqi CMS template support `if`, `elif`, `else` logical judgments?

In Anqi CMS template design, conditional logic judgment is an indispensable part for realizing dynamic content display and complex layout control.As a website operator, I am well aware that flexibly using `if`, `elif`, `else` and other logical judgment tags can allow us to present a wide variety of page content based on different data states or business requirements, thereby enhancing user experience and the interactivity of the website.The Anqi CMS template engine supports syntax similar to the Django template engine, which allows users familiar with other mainstream CMS template languages to quickly get started

2025-11-06

How to implement and display pagination navigation on list pages (such as article lists, search results)?

As an experienced CMS website operations personnel for an Internet security company, I know that the details of content presentation are crucial for user experience and website SEO.Page navigation is one of the fundamental and key components, which not only helps users efficiently browse a large amount of content, but also allows search engines to better crawl and index website information.Today, I will elaborate on how to elegantly display pagination navigation on the list page of AnQi CMS, such as article lists, search result pages, etc.### Overview of Pagination Mechanism in AnQi CMS Implementing pagination functionality in AnQi CMS is intuitive and efficient

2025-11-06

How to retrieve and display the list of友情链接 configured in the background?

As an experienced CMS website operation personnel, I fully understand the importance of efficient content management and front-end display for the success of the website.Friend links are an important part of a website's external cooperation and SEO optimization, and their convenient acquisition and display methods are an indispensable part of daily operation.Now, I will elaborate on how to obtain and display the list of友情链接 links configured in the AnQiCMS admin panel.### AnQi CMS: Efficient management and display of the background friendship link list Friendship links, as an important part of website external link construction

2025-11-06

How to define a temporary variable and perform assignment operations in a template?

Hello! As an experienced AnQi CMS website operator, I am very happy to be able to explain in detail how to define and assign temporary variables in AnQi CMS templates.This is crucial for achieving the flexibility, readability, and maintainability of templates, enabling us to organize and display website content more efficiently.In the Anqi CMS template system, we often encounter scenarios where we need to store data, calculate results, or prepare content for specific components locally.To meet these requirements, Anqi CMS provides a concise and powerful variable definition mechanism, mainly realized through two tags

2025-11-06

What are the different roles of the three auxiliary tags `include`, `extends`, and `macro` in template structure organization?

As an experienced CMS website operation personnel of AnQi, I am well aware of the importance of a clear and efficient template structure for content management and website maintenance.In AnQi CMS, the template engine provides various auxiliary tags to help us better organize and reuse template code, among which `include`, `extends`, and `macro` are the three great tools for building a flexible template architecture.They each have different responsibilities, but together they serve to enhance the maintainability and development efficiency of the template.### Modular content reuse

2025-11-06

How to use built-in filters (such as `truncatechars`, `upper`) to process and convert the data format of template variables?

As an experienced AnQiCMS website operation person, I am fully aware of the importance of content in attracting and retaining users.High-quality content not only requires careful creation, but also needs to be presented in an appropriate format and optimized to enhance user experience and readability.AnQi CMS, with its flexible Django template engine syntax, provides us with powerful built-in filter functions, allowing us to easily process and convert the data format of template variables.Next, I will give a detailed introduction on how to use the built-in filter of Anqi CMS

2025-11-06

What file extension should AnQiCMS template files use?

As an experienced AnQi CMS website operation personnel, I know that template files play a core role in building a flexible and efficient website.They not only carry the visual presentation of the website, but also serve as a bridge for content and user interaction.For Anqi CMS, understanding the composition and usage specifications of its template files is the foundation for efficient content management and website optimization.According to the official document of Anqi CMS, template files uniformly use the file extension `.html`.

2025-11-06