Home > Article > Backend Development > How to convert Unix timestamp to date time format using PHP
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:
652bad69a3fb5b787fb5f187a75f147e
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:
3d7a3b1a60a20463857810a3d09a99b4format('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:
879045783930fa8b52a77b28c1d9fafc
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!