Unix timestamp refers to the total number of seconds from 0:00:00 on January 1, 1970 to the current time. It is a time representation standard used by Linux and Unix systems and is also widely used. Web development in progress. In PHP, we can convert Unix timestamp to date time format to better present time information. This article will explain how to convert Unix timestamp to datetime format in PHP.
In PHP, use the date() function to convert a Unix timestamp to date-time format. The first parameter of this function is the date format, and the second parameter is the Unix timestamp. If the second parameter is not specified, the current timestamp will be used by default.
For example, the following code converts Unix timestamp to date time format:
<?php $timeStamp = 1612888400; $date = date('Y-m-d H:i:s', $timeStamp); echo $date; ?>
The output result is:
2021-02-09 16:00:00
Here, we convert Unix timestamp 1612888400 to date time Format.
In PHP 5.2 and above, you can use the DateTime class to convert Unix timestamps to date-time format. First, we need to create an object of DateTime class, and then use the format() method to specify the date and time format.
The following is a sample code that uses the DateTime class to implement Unix timestamp conversion:
<?php $timeStamp = 1612888400; $dateTime = new DateTime("@$timeStamp"); $date = $dateTime->format('Y-m-d H:i:s'); echo $date; ?>
The output result is still:
2021-02-09 16:00:00
Here, we created an object of the DateTime class$ dateTime and pass it a Unix timestamp as a parameter. We then use the format() method to specify the datetime format as 'Y-m-d H:i:s'.
#If you want to convert a Unix timestamp to a localized date and time format, you can use the strftime() function . This function can convert any datetime to a local format based on a localized datetime format string.
The following is a sample code for Unix timestamp conversion using the strftime() function:
<?php $timeStamp = 1612888400; setlocale(LC_TIME, 'zh_CN.utf8'); // 将日期时间转换为中文格式 $date = strftime('%Y年%m月%d日 %H时%M分%S秒', $timeStamp); echo $date; ?>
The output result is:
2021年02月09日 16时00分00秒
Here, we use the setlocale() function to set the local The locale is Chinese, and then use the strftime() function to specify the date and time format as '%Y year %m month %d day %H hour %M minute %S second'.
Summary
In PHP, you can use the date() function, DateTime class, and strftime() function to convert Unix timestamp to date and time format. No matter which method is used, we need to know the format of the date time in order to convert the Unix timestamp to the corresponding date time. In development, understanding these techniques can help us better handle time-related information.
The above is the detailed content of How to convert Unix timestamp to date time format using PHP. For more information, please follow other related articles on the PHP Chinese website!