In AnQiCMS (AnQiCMS), when you retrieve various information such as documents, categories, attachments, users, and more through the API interface, you will find that likecreated_time(creation time) andupdated_time(Update time) such fields are usually presented in integer form. This is indeed the common Unix timestamp format used by many systems, including AnQiCMS.
What is a Unix timestamp?
Unix timestamp, also known as POSIX time or Epoch time, is a way of representing time that represents time as the number of seconds elapsed since 00:00:00 UTC on January 1, 1970, which is the Unix epoch, Unix Epoch.It is a pure number, which does not contain any time zone or localization information, and therefore has a very high degree of universality and consistency in cross-system, cross-language data exchange.AnQiCMS uses this format to facilitate data storage, transmission, and flexible handling in different application environments.
Why does AnQiCMS use Unix timestamps?
There are several significant advantages to using Unix timestamps:
- High storage efficiency:Compared to complex date-time strings, integer-type Unix timestamps take up less storage space.
- Calculation is convenient:Date and time interval calculation (for example, calculating how many days since the item was released) can be completed by simple integer addition and subtraction.
- Cross-platform compatibility:Almost all programming languages and database systems natively support the parsing and conversion of Unix timestamps, reducing the barriers to time data processing between different systems.
- Time zone independence:The timestamp itself does not contain timezone information, it always represents UTC time, which means you can get it anywhere and convert it to any specific timezone time as needed.
How to convert Unix timestamp to a readable date and time format?
Although Unix timestamps are very efficient in machine processing, for users, a string of numbers is obviously not as intuitive as the format "October 27, 2023, 14:30:00".Therefore, in front-end display or back-end business logic, we usually need to convert it into a date and time string that is easier to understand.
Here are several common conversion methods in various programming languages:
1. JavaScript (Frontend or Node.js)
JavaScript'sDateThe object accepts millisecond timestamps by default. Since AnQiCMS returns second-level timestamps, you need to multiply it by 1000.
const unixTimestamp = 1662717106; // 示例:来自AnQiCMS的updated_time
const date = new Date(unixTimestamp * 1000);
// 转换为本地时间字符串
console.log(date.toLocaleString()); // 例如: "2022/9/9 下午1:51:46" (根据您的系统设置)
// 转换为特定格式(例如:YYYY-MM-DD HH:mm:ss)
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始
const day = date.getDate().toString().padStart(2, '0');
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
console.log(formattedDate); // 例如: "2022-09-09 13:51:46"
2. PHP (Backend)
PHP'sdate()The function can directly handle Unix timestamps, the second parameter is the timestamp.
$unixTimestamp = 1662717106; // 示例:来自AnQiCMS的updated_time
// 转换为可读格式
$formattedDate = date('Y-m-d H:i:s', $unixTimestamp);
echo $formattedDate; // 例如: "2022-09-09 13:51:46"
3. Python (Backend)
Python can be useddatetimeto convert modules.
import datetime
unix_timestamp = 1662717106 # 示例:来自AnQiCMS的updated_time
# 将时间戳转换为datetime对象
dt_object = datetime.datetime.fromtimestamp(unix_timestamp)
# 格式化为字符串
formatted_date = dt_object.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_date) # 例如: "2022-09-09 13:51:46"
4. Go (AnQiCMS underlying language, backend)
If you are developing in Go language, AnQiCMS itself is written in Go, and its time handling is consistent with this.
package main
import (
"fmt"
"time"
)
func main() {
unixTimestamp := int64(1662717106) // 示例:来自AnQiCMS的updated_time
// 将秒级时间戳转换为time.Time对象
t := time.Unix(unixTimestamp, 0)
// 格式化为字符串
formattedDate := t.Format("2006-01-02 15:04:05") // Go语言独特的格式化参考时间
fmt.Println(formattedDate) // 例如: "2022-09-09 13:51:46"
}
What should be noted when converting?
When performing timestamp conversion, there are several details to pay attention to:
- Time zone:Unix timestamp is based on UTC, but when converted to a string, many library functions (such as JavaScript's
toLocaleString()) It will use the time zone of your system by default. If you need to display a specific time zone (such as the time zone of the server or fixed to UTC), please make sure to specify it clearly when converting or formatting.For example, of JavaScript'stoUTCString()ortoISOString()methods can obtain UTC time. - Millisecond vs. Second:To emphasize again, AnQiCMS returnssecondstimestamp, while JavaScript's
Dateconstructor needsmilliseconds. Remember to multiply by 1000 in JavaScript. Other languagesfromtimestampordatefunctions usually handle second-level timestamps by default. - Formatting string:Different programming languages have their own placeholder conventions for formatting date and time strings (for example
Y-m-d/%Y-%m-%d/2006-01-02etc.), please refer to the documentation of the corresponding language.
By following the above methods and precautions, you can easily convert the Unix timestamp provided by AnQiCMS into various readable date and time formats, thereby better displaying and processing time information on your website or application.
Frequently Asked Questions (FAQ)
Why does AnQiCMS not return formatted time strings directly but use Unix timestamps instead?The use of Unix timestamps has many technical advantages, such as higher database storage efficiency, ease of cross-language and cross-system data exchange, and direct calculation of time intervals.What is more important is that it is unrelated to specific time zones and display formats, which provides developers with great flexibility to freely convert timestamps to any desired date-time format and time zone on either the client or server, according to different application scenarios and user needs.
What is in the document?
created_timeorupdated_timeWhat does it mean if the field is displayed as 0?Answer: Ifcreated_timeorupdated_timeThe value is 0, usually indicating that the time information of the document or record has not been set or initialized.In Unix timestamps, 0 represents the Unix epoch (UTC January 1, 1970, 00:00:00).In practical applications, if such a situation is encountered, it may be necessary to check the data source or system configuration to see why these fields are not assigned correctly.Can I directly set the display format of these time fields in the AnQiCMS backend?Answer: The AnQiCMS backend usually does not provide a direct function to change the timestamp format of the API response, as the API design tends to provide raw, general data formats.If you want to display time in a specific format on the website frontend or a custom template, you need to use the programming language methods mentioned above (such as JavaScript, PHP) to convert and format the timestamp returned by the API to achieve the display effect you want.