Home  >  Article  >  Backend Development  >  Related introduction to php timestamp conversion

Related introduction to php timestamp conversion

PHPz
PHPzOriginal
2023-03-29 10:14:00913browse

Time stamp refers to the time format of the Unix operating system, which is based on the number of seconds at 00:00:00 on January 1, 1970 (UTC/GMT). Because this format is easy to calculate and compare, timestamps are widely used in network programming and database applications. In PHP, timestamps can be easily converted to readable date and time formats with a simple function call.

In PHP, timestamp conversion requires the use of a built-in function - date(), which can format Unix timestamps into specified date and time strings . The specific usage is as follows:

$timestamp = time(); // 获取当前时间戳
$date = date("Y-m-d H:i:s", $timestamp); // 将时间戳格式化为日期时间字符串
echo $date;

In the above code, the time() function is used to obtain the Unix timestamp of the current time, while the date() function will The timestamp is formatted in the string format of Y-m-d H:i:s. Among them, Y represents the year, m represents the month, d represents the date, H represents the hour, and i represents the minute. , s represents the number of seconds.

In addition to directly calling the date() function for conversion, PHP also provides some other useful functions, such as strtotime() and DateTime class to handle timestamps more flexibly. For example, you can use the strtotime() function to parse a string date into a Unix timestamp, and then use the date() function to format it into a specific date and time string:

$str = '2021-09-01 12:00:00'; // 定义一个日期字符串
$timestamp = strtotime($str); // 将字符串解析为Unix时间戳
$date = date("Y/m/d", $timestamp); // 将时间戳格式化为年/月/日格式的字符串
echo $date;

In addition, the DateTime class in PHP can handle dates and times more efficiently. You can use the createFromFormat() method to convert a string date into a DateTime object and format it into a specific date and time string using the format() method:

$str = '2021-09-01 12:00:00'; // 定义一个日期字符串
$datetime = DateTime::createFromFormat('Y-m-d H:i:s', $str); // 将字符串解析为DateTime对象
$date = $datetime->format('Y年m月d日 H:i:s'); // 将DateTime对象格式化为字符串
echo $date;

By using these functions and classes, developers can quickly and easily Easily convert between Unix timestamps and date and time strings, and improve efficiency and quality during the development process.

The above is the detailed content of Related introduction to php timestamp conversion. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn