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(Update time) are two very critical fields. Many users may be curious about what these values that look like a string of numbers actually are?They are actually standard Unix timestamps.

Understanding Unix timestamps

Unix timestamp, also known as POSIX time, is the total number of seconds from Coordinated Universal Time (UTC) on January 1, 1970, to the present. For example, you can see similar examples in the document details or list interface returns of AnQiCMS.1607308159Such a number.

This representation has many advantages:

  1. Concise and compact: It is a pure number, taking up little storage space, convenient for storage in databases and transmission over the network.
  2. UniformityIt is a globally unified time standard that does not involve time zone differences, making it convenient for users and systems in different regions to synchronize and calculate time.
  3. Easy to compare: Since it is pure numbers, it can be directly compared in size, making it easy to determine which time is earlier or later.
  4. Cross-platform compatibilityUnix timestamp support is built into almost all programming languages and operating systems, making it very convenient for exchanging data between different technical stacks.

Convert Unix timestamp to readable date

If we have understood that they are Unix timestamps, then how can we convert these numbers into the year-month-day hour:minute:second format that we are accustomed to reading?This process is not complicated, the core idea is that the Unix timestamp returned by AnQiCMS is in "seconds" units, while many programming languages' date processing functions need "milliseconds" units.So, the first step in the conversion is often to multiply the timestamp by 1000.

The following are some common conversion methods in programming languages or scenarios:

1. JavaScript (Front-end pages or Node.js)

You can use in JavaScript,DateAn object is used to handle timestamps. It is important to note that JavaScript'sDateThe object constructor receives milliseconds, so the second-level Unix timestamp needs to be multiplied 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 Unix timestamps in seconds 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 data exported from AnQiCMS (for example, CSV or JSON converted to a table) in Excel or Google Sheets, you can also convert it.

  • Google Sheets:Assuming the timestamp is in cell A1, you can enter a 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 a formula in cell B1.=(A1/86400)+DATE(1970,1,1)+8/24(If your Excel is in the UTC+8 time zone, you need to add an 8-hour time difference,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/detailObtain document details,archive/listGet the document list, orcategory/detail/comment/listother interfaces mentioned in the document, as long ascreated_timeorupdated_timethey are in Unix timestamp format (intReturns in the form of type). 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 display them on the website front end, log them on the back end, or use them in data analysis.

Mastering the Unix timestamp conversion method allows 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.


Frequently Asked 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 formatUniformity, conciseness, and universality. Timestamps do not contain timezone information, making them easy to calculate and synchronize 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 pages, APPs, or back-end services that call APIs), so that 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 the AnQiCMS background?A2: In most cases, AnQiCMS's API interface is standardized, returning Unix timestamps uniformly, and does not provide the function to directly modify the date format of the API return in the background. The conversion and display of the date format is usually inCall the API clientDone, this can maximize the universality of the API, and allow developers to customize it according to specific application scenarios.

Q3: When converting timestamps, I found that the converted date is inaccurate, several hours later or earlier than my local time. What's the matter?A3: This is likely to beTime zone issueCaused. The Unix timestamp 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 deviate from the expected one.When converting, make sure to set or consider the time zone according to your needs, for example, you can use it in JavaScript.toUTCString()Check the UTC time, or use a dedicated date-time library (such as Moment.js, Date-fns) for more precise time zone conversion management.