When developing with PHP, it is often necessary to convert timestamps into an easy-to-understand time format. This article will explain how to use PHP to convert timestamps to common time formats.
Use PHP's date() function to format a timestamp into date format. This function has two parameters, the first parameter is the date format, and the second parameter is the timestamp. The following is a sample code that converts a timestamp to date format:
$timestamp = time(); // 获取当前时间戳 $date = date('Y-m-d H:i:s', $timestamp); // 将时间戳转换为日期格式 echo $date;
In the above code, the first parameter of the date() function is the date format, and the second parameter is the timestamp. As shown in the above example, the date format can be year (Y), month (m), date (d), hour (H), minute (i), second (s), etc.
In addition to date format, we can also convert timestamp to day of week. PHP provides a function date() function parameter "l" that can return the day of the week information of the current date. The following is a sample code that converts a timestamp to a day of the week:
$timestamp = time(); // 获取当前时间戳 $week = date('l', $timestamp); // 将时间戳转换为周几 echo $week;
In the above code, the first parameter of the date() function is "l", which represents the day of the week that returns the current date.
Sometimes we need to convert timestamp to time in a specific format. In this case, you can use PHP's date() function for formatting. The following is a sample code that converts a timestamp to a specified time format:
$timestamp = time(); // 获取当前时间戳 $time = date('F jS, Y \a\t h:i A', $timestamp); // 将时间戳转换为特定格式 echo $time;
In the above code, the method of converting a timestamp to a specified time format is to pass a specific date format parameter to the date() function. In this example, the date format is "F jS, Y \a\t h:i A".
In addition to converting timestamp to time format, we can also convert time format to timestamp format for later used during operation. PHP provides a function strtotime() that can convert the time format into timestamp format. The following is a sample code that converts time to timestamp format:
$time = '2021-01-01 10:00:00'; // 需要转换的时间 $timestamp = strtotime($time); // 将时间转换为时间戳格式 echo $timestamp;
In the above code, the strtotime() function converts the time format "2021-01-01 10:00:00" to timestamp format .
Summary
In PHP development, timestamp and time format are two concepts that are often used. We can convert by using PHP's date() function and strtotime() function. This article details how to convert a timestamp to date format, convert a timestamp to a day of the week, convert a timestamp to a specified time format, and how to convert a time to a timestamp format. In actual development, we can choose and use it as needed.
The above is the detailed content of How to convert timestamp to common time format in PHP. For more information, please follow other related articles on the PHP Chinese website!