Home  >  Article  >  Backend Development  >  How to convert timestamp into readable date and time format in php

How to convert timestamp into readable date and time format in php

PHPz
PHPzOriginal
2023-03-29 16:24:39460browse

PHP is a very popular programming language that is widely used in server-side programming, web development, and database management. A timestamp refers to the way a specific date and time is represented on a computer, usually as an integer. In PHP, we can convert timestamps into human-readable date and time formats for better presentation to users.

The following is a simple PHP script that can convert a timestamp into an easy-to-read date and time format:

<?php
$timestamp = 1599438715; // 时间戳
$date = date(&#39;Y-m-d H:i:s&#39;, $timestamp); // 将时间戳转化为日期和时间
echo $date; // 输出结果:2020-09-07 11:38:35
?>

In the above code, we first define a timestamp, and then Use PHP's date() function to convert it to date and time format. The first parameter of the date() function is the formatted string of date and time, and the second parameter is the timestamp to be converted. In this example, we convert the timestamp into the format "Year-Month-Day Hour:Minute:Second" and store the result in the $date variable. Finally, use echo to print out the results.

In addition to the method demonstrated in the above example, you can also use PHP's strtotime() function to convert a string into a timestamp, and then convert the timestamp into date and time format. For example:

<?php
$str_time = &#39;2020-09-07 11:38:35&#39;; // 需要转换的字符串
$time = strtotime($str_time); // 将字符串转换为时间戳
$date = date(&#39;Y-m-d H:i:s&#39;, $time); // 将时间戳转换为日期和时间
echo $date; // 输出结果:2020-09-07 11:38:35
?>

The above code will convert a string containing date and time into a timestamp, then use the date() function to convert the timestamp into date and time format, and print the result.

In short, converting timestamps to date and time formats is very simple in PHP. We can easily implement this function by simply using the date() function or strtotime() function to better present time information in web applications.

The above is the detailed content of How to convert timestamp into readable date and time format in php. 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