The timestamp refers to the number of seconds since January 1, 1970 00:00:00 GMT. In many cases, we need to convert a specific time into a timestamp to facilitate time calculation and comparison. PHP provides some simple functions to help convert time into timestamp.
There are two main ways to convert time to timestamp in PHP:
strtotime The () function is a commonly used time function in PHP, which can convert a specific time format into a timestamp. For example, our code to convert "2020-03-10 16:30:00" into a timestamp is as follows:
$time = strtotime("2020-03-10 16:30:00"); echo $time; //输出1583847000
In the above code, the strtotime() function parses the date and time in the string, Automatically calculate the number of seconds between 00:00:00 on January 1, 1970, and convert it into a timestamp.
The DateTime class introduced in PHP5 provides a more object-oriented way to deal with dates and times. We can use the format() method in the DateTime class to convert a formatted date string into a timestamp. For example, the code we use to convert "2020-03-10 16:30:00" into a timestamp is as follows:
$date = new DateTime("2020-03-10 16:30:00"); $time = $date->format('U'); echo $time; //输出1583847000
In the above code, we use the new keyword to create a DateTime object and set the time Strings are initialized as arguments to the constructor. Next, we use the format() method in the DateTime class with "U" as the parameter to convert the time into a timestamp.
It should be noted that when using the DateTime class, you also need to specify the format of the time string. In this example, the format of the time string we specify is "Y-m-d H:i:s", that is, year-month-day hour:minute:second.
Summary:
There are two main ways to convert time into timestamp in PHP, one is to use strtotime() function, the other is to use DateTime format() method in the class. No matter which method is used, we can easily convert the specific time format into a timestamp to facilitate time calculation and comparison.
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!