Home >Backend Development >PHP Problem >How to change php time to timestamp
When programming in PHP, it is often necessary to convert between different time formats. For example, change the datetime format to timestamp format. In this article, we will explain how to convert date and time to timestamp format using PHP.
In PHP, use the strtotime() function to convert date time format to timestamp format. The strtotime() function receives a date and time string and returns its corresponding timestamp.
The following is an example of converting date time format to timestamp format:
$date = "2021-07-12 15:30:00"; $timestamp = strtotime($date); echo $timestamp; //输出:1626095400
In the above example, we first define a date time string $date, and then use strtotime() The function converts it to timestamp format and saves the result in the $timestamp variable. Finally, use the echo statement to output the results in timestamp format.
If you need to convert the current date and time to timestamp format, you can use PHP’s built-in time() function .
The following is an example of converting the current date and time into timestamp format:
$timestamp = time(); echo $timestamp; //输出:1629179905
In the above example, we use the time() function to get the timestamp of the current time and convert the result Saved in the $timestamp variable. Finally, use the echo statement to output the results in timestamp format.
If you need to convert timestamp format to date time format, you can use PHP's built-in date() function. The date() function receives two parameters: the first parameter is the date and time format, and the second parameter is the timestamp. The function returns the datetime string corresponding to the timestamp.
The following is an example of converting timestamp format to datetime format:
$timestamp = 1626095400; $date = date("Y-m-d H:i:s", $timestamp); echo $date; //输出:2021-07-12 15:30:00
In the above example, we first define a timestamp $timestamp. Then, use the date() function to convert the timestamp to datetime format and save the result in the $date variable. Finally, use the echo statement to output the results in date and time format.
In this article, we covered how to convert datetime format to timestamp format, convert current datetime to timestamp format using PHP, and Convert timestamp format to datetime format. These functions are very useful and can help us better handle dates and times when writing PHP programs.
The above is the detailed content of How to change php time to timestamp. For more information, please follow other related articles on the PHP Chinese website!