If you are developing a PHP-based project or application, you will inevitably need to work with time and date. In many cases, converting dates and times to timestamps can make your programming more convenient and reliable. In this article, we will explain how to convert date and time to timestamp in PHP.
1. What is a timestamp?
A timestamp is a numeric value representing a date and time that represents the number of seconds that have elapsed since 00:00:00 on January 1, 1970. Timestamps are often used to calculate the time difference between two dates/times. In PHP, use the time() function to get the timestamp of the current time.
2. Convert date to timestamp
To convert date to timestamp, you can use the strtotime() function. This function parses a date string into a timestamp. Here is a sample code:
$dateString = '2022-01-01'; $timeStamp = strtotime($dateString); echo $timeStamp;
The above code will output: 1640976000. This value represents the number of seconds since January 1, 1970, on the date "2022-01-01".
3. Convert time to timestamp
If you need to convert time to timestamp, you need to append the time to the date string. For example, to convert 2:30 PM to a timestamp, you can use the following code:
$timeString = '2022-01-01 14:30:00'; $timeStamp = strtotime($timeString); echo $timeStamp;
The above code will output: 1641000600. This value represents the number of seconds since 13:30:00 on January 1, 1970, at the time "2022-01-01 14:30:00".
4. Convert the current time to a timestamp
If you need to get the timestamp of the current time, you can use PHP's built-in time() function. Here is a sample code:
$currentTime = time(); echo $currentTime;
The above code will output the timestamp of the current time, for example: 1641240155.
5. Summary
Converting date and time to timestamp in PHP is a common task. Use the strtotime() function to parse date and time strings into timestamps, and the time() function to get the timestamp of the current time. Having this knowledge can help you calculate time and date more conveniently and accurately.
The above is the detailed content of How to convert time to timestamp in php. For more information, please follow other related articles on the PHP Chinese website!