When using AnQiCMS, we often obtain detailed information or lists of documents or other content from the API interface. In these returned data,created_time(Creation time) andupdated_time(Updated time) are two very critical fields.Many users may be curious, what are these values that look like a series of numbers?They are actually standard Unix timestamps.
Understanding Unix timestamp
Unix timestamp, also known as Posix time, is the total number of seconds from 00:00:00 UTC on January 1, 1970, to the present. For example, you can see something similar in the document details or list interface examples returned by AnQiCMS.1607308159Such a number.
This representation has many advantages:
- Concise and compact: It is a pure number, occupies less storage space, and is convenient for storage in databases and network transmission.
- UniformityIt is a globally unified time standard that does not involve time zone differences, convenient for users and systems in different regions to synchronize and calculate time.
- Easy to compareSince it is purely numeric, it can be directly compared in size, making it easy to determine which time is earlier or later.
- Cross-platform compatibility:Almost all programming languages and operating systems are built-in with support for Unix timestamps, making it very convenient to exchange data between different technical stacks.
Convert Unix timestamp to readable date
How can we convert these numbers to the year-month-day hour:minute:second format that we are accustomed to reading in our daily lives?This process is not complicated, the core idea is: The Unix timestamp returned by AnQiCMS is in "secondsSo, the first step in the conversion is often to multiply the timestamp by 1000.
Here are some common conversion methods for programming languages or scenarios:
1. JavaScript (front-end page or Node.js)
In JavaScript, you can useDateThe object is used to handle timestamps. It is worth noting that JavaScript'sDateThe object constructor receives milliseconds, so you need to multiply the second-level Unix timestamp by 1000.
const unixTimestamp = 1607308159; // 例如,从AnQiCMS API返回的created_time
const date = new Date(unixTimestamp * 1000); // 转换为毫秒并创建Date对象
// 转换为本地可读日期字符串
const readableDate = date.toLocaleString(); // 例如:"2020/12/7 下午3:49:19" (根据地区和浏览器设置)
// 如果需要特定格式(如 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); // 例如:"2020-12-07 15:49:19"
2. PHP (Backend Processing)
In PHP,date()The function can directly handle second-level Unix timestamp without the need to multiply by 1000.
<?php
$unixTimestamp = 1607308159; // 从AnQiCMS API返回的created_time
// 将Unix时间戳格式化为可读日期字符串
$readableDate = date('Y-m-d H:i:s', $unixTimestamp);
echo $readableDate; // 输出:"2020-12-07 15:49:19"
// 你也可以根据需要调整日期格式,例如只显示日期
$onlyDate = date('Y-m-d', $unixTimestamp);
echo $onlyDate; // 输出:"2020-12-07"
?>
3. Python (backend script or data processing)
Python'sdatetimeThe module provides powerful date and time processing capabilities.
import datetime
unix_timestamp = 1607308159 # 从AnQiCMS API返回的created_time
# 将Unix时间戳转换为datetime对象
datetime_object = datetime.datetime.fromtimestamp(unix_timestamp)
# 格式化为可读日期字符串
readable_date = datetime_object.strftime('%Y-%m-%d %H:%M:%S')
print(readable_date) # 输出:"2020-12-07 15:49:19"
4. View in Excel or Google Sheets
If you want to view the date in Excel or Google Sheets when you export data from AnQiCMS (such as CSV or JSON converted to a table), you can also perform the conversion.
- Google Sheets:Assuming the timestamp is in cell A1, you can enter the formula in cell B1.
=(A1/86400)+DATE(1970,1,1)Then set the format of cell B1 to date and time. - Excel:Assuming the timestamp is in cell A1, you can enter the formula in cell B1.
=(A1/86400)+DATE(1970,1,1)+8/24(如果你的Excel是UTC+8时区,需要加上8小时的时差,8/24Represents 8 hours), then set the format of cell B1 to date and time.
Actual application
In the actual application of AnQiCMS, whether througharchive/detailto get document details,archive/listGet document list, orcategory/detail/comment/listetc., as long as the document mentionscreated_timeorupdated_timethey are all in Unix timestamp format,intType)的形式返回。This means you can easily convert them into a readable date format using any of the above methods, according to your development environment and needs, so that you can better use these key time information in front-end display, backend logging, or data analysis.
Mastering the Unix timestamp conversion method will allow you to handle the time data returned by AnQiCMS more flexibly. Whether it is for page display, data analysis, or other backend logic, you can do it with ease.
Common Questions (FAQ)
Q1: Why does AnQiCMS use Unix timestamps instead of returning readable date strings directly?A1: AnQiCMS returns Unix timestamp mainly to maintain data format consistencyUniformity, simplicity, and universality.Timestamp does not include time zone information, making it easy to perform calculations and synchronization across different systems and time zones, while occupying less storage space.The work of converting timestamps to readable date strings is left to the client (front-end page, APP, or back-end service calling the API), so it can be formatted flexibly according to the user's local time zone or specific display requirements, providing a better user experience.
Q2: Can I directly set the date format of the API return in AnQiCMS backend?A2: Generally speaking, AnQiCMS's API interfaces are standardized, and uniformly return Unix timestamps without providing the functionality to directly modify the date format of the API return in the background. The conversion and display of date formats should usually be inCall the API clientCompleted, which can maximize the universality of the API and allow developers to customize according to specific application scenarios.
Q3: When converting timestamps, I find that the converted date is inaccurate and is several hours later or earlier than my local time. What's going on?A3: This is very likelyTime zone issuecaused.The Unix timestamp itself is based on UTC (Coordinated Universal Time), and does not contain any timezone information.When you convert it to a readable date in a programming language, if the code does not explicitly specify a time zone, the system or programming language may default to using the local time zone of the server or running environment.For example, if your server is in the UTC+8 time zone but your code does not handle it correctly, it may cause the displayed time to be different from the expected.toUTCString()Check the UTC time or use a specialized date-time library (such as Moment.js, Date-fns) for more accurate timezone conversion.