Home >Backend Development >PHP Problem >Example showing how to convert PHP time to timestamp
PHP is a popular programming language used by many web developers to build powerful web applications. When dealing with time-related data, it is very common to use timestamps. A timestamp is an integer value that represents the number of seconds from the beginning of the Unix epoch to the current time. When we need to get the timestamp from the time string, we can do it through PHP's built-in function. In this article, we will show how to convert PHP time to timestamp.
There is a built-in function strtotime() in PHP that can convert a time string into a timestamp. The first parameter of the strtotime() function is a time string, and the second parameter is optional. The date and time format is specified in the first parameter. We can use the following sample code to convert a time string to a timestamp:
$timestamp = strtotime('2020-01-01 00:00:00'); echo $timestamp;
Output result:
1577836800
in PHP The DateTime class provides an object-oriented way to work with dates and times. The DateTime class can convert a time string into a DateTime object and then convert it into a timestamp using the getTimestamp() method. The following is a sample code using the DateTime class:
$date = new DateTime('2020-01-01 00:00:00'); $timestamp = $date->getTimestamp(); echo $timestamp;
Output result:
1577836800
We can also define a custom function, Convert a time string to a timestamp. Here is a sample code using a custom function:
function strToTimestamp($str) { $date = DateTime::createFromFormat('Y-m-d H:i:s', $str); return $date->getTimestamp(); } $timestamp = strToTimestamp('2020-01-01 00:00:00'); echo $timestamp;
Output result:
1577836800
Conclusion
In PHP, there are multiple ways to convert a time string to timestamp. This functionality can be achieved whether you use built-in functions, the DateTime class, or custom functions. Which method you choose depends on personal preference and job requirements. Hope this article is helpful to you.
The above is the detailed content of Example showing how to convert PHP time to timestamp. For more information, please follow other related articles on the PHP Chinese website!