In AnQiCMS, when you obtain various information such as documents, categories, attachments, and users through the API interface, you will find that likecreated_time(Creation time) andupdated_time(Updated Time) This field is usually presented in integer form. This is indeed a common timestamp format used by many systems, including AnQiCMS.
What is Unix timestamp?
Unix timestamp, also known as POSIX time or Epoch time, is a way to represent time, which expresses time as the number of seconds elapsed since 00:00:00 UTC on January 1, 1970 (that is, the Unix Epoch, Unix Epoch).It is a pure number, without any timezone or localization information, and therefore has very high universality and consistency in cross-system and cross-language data exchange.AnQiCMS uses this format precisely to facilitate data storage, transmission, and flexible handling in different application environments.
Why does AnQiCMS use Unix timestamp?
There are several significant advantages to using Unix timestamp:
- High storage efficiency:Compared to complex date-time strings, integer Unix timestamps occupy less storage space.
- Easier calculation:Date and time interval calculation (such as, calculating how many days have been published) can be completed directly through 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 time data processing barriers between different systems.
- Time zone independence:The timestamp itself does not carry timezone information, always representing UTC time, which means you can obtain it anywhere and convert it to any specific timezone as needed.
How to convert Unix timestamp to a readable date and time format?
Although Unix timestamps are very efficient for machine processing, a string of numbers is clearly not as intuitive for users as a format like '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-time string that is easier to understand.
Here are several common conversion methods in various programming languages:
1. JavaScript (front-end or Node.js)
JavaScript'sDateObjects default to accepting millisecond timestamps. Since AnQiCMS returns second-level timestamps, you need to multiply them 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()Functions 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 useddatetimemodules for conversion.
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 it.
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 you pay attention to during the conversion?
When performing timestamp conversion, there are several details to be aware of:
- Time zone:Unix timestamps are based on UTC, but when converted to a string, many library functions (such as JavaScript's
toLocaleString()The system will use the current time zone of your system by default.If you need to display a specific timezone (such as the timezone of the server or fixed to UTC), make sure to specify it explicitly when converting or formatting.toUTCString()ortoISOString()methods can obtain the UTC time. - Milliseconds vs. Seconds:It is emphasized again that AnQiCMS returns:secondstimestamp levels, while JavaScript's
Dateconstructor needsmillisecondRemember to multiply by 1000 in JavaScript. The other languages.fromtimestampordateFunctions usually handle timestamp in seconds by default. - Formatted 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 Unix timestamps provided by AnQiCMS into various readable date and time formats, thus better displaying and processing time information on your website or application.
Common Questions (FAQ)
Question: Why does AnQiCMS not directly return a formatted date string, but use Unix timestamps instead?Answer: There are many technical advantages to using Unix timestamps, such as higher database storage efficiency, ease of data exchange across languages and systems, and a more direct calculation of time intervals.It is more important that it is unrelated to specific time zones and display formats, which provides great flexibility for developers. They can freely convert timestamps into any required date-time format and time zone according to different application scenarios and user needs on either the client side or the server side.
Question: In the documentation of
created_timeorupdated_timeWhat does it mean if the field is displayed as 0?Answer: Ifcreated_timeorupdated_timeThe value of the field is 0, typically indicating that the time information of the document or record has not been set or initialized.In Unix timestamp, 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.Question: Can I directly set the display format of these time fields in the AnQiCMS backend?Answer: AnQiCMS backend usually does not provide a direct function to change the timestamp format of API interface return, because the API design tends to provide original, general data format.If you wish 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 desired display effect.